验证随时间变化的连续条件

2024-05-08

我想开发一个Python程序,从某个时刻开始,等待60秒再执行操作。该程序必须具有的另一个功能是,如果我更新初始时间,它必须开始检查条件。我想过用线程来做,但我不知道如何停止线程并以新的开始时间重新启动它。

import thread
import time


# Define a function for the thread
def check_message (last, timer):
    oldtime = time.time()
    print oldtime
    # check
    while time.time() - oldtime <= 60:
    print (time.time() - oldtime)
    print "One minute"+ str(time.time())
    return 1

# Create two threads as follows
try:
    named_tuple = time.localtime() # get struct_time
    time_string = time.strftime("%H:%M:%S", named_tuple)
    thread.start_new_thread(check_message , (time_string, 60))
except:
    print "Error: unable to start thread"

while 1:
    pass

Thanks!


在这里检查循环中的时间可能没有必要,而且很浪费,因为您可以将线程置于睡眠状态,并在时间到时让内核将其唤醒。 线程库提供threading.Timer https://docs.python.org/3/library/threading.html#timer-objects对于此类用例。您的情况的困难在于,您无法中断这样的睡眠线程来调整执行指定函数的时间间隔。

我正在使用自定义管理器类TimeLord在我下面的例子中,为了克服这个限制。TimeLord通过取消当前计时器并将其替换为新计时器来启用“重置”计时器。 以此目的TimeLord包含一个包装中间工作函数和一个“令牌”属性,必须由正在运行的计时器实例弹出才能执行指定的目标函数。

这种设计保证了指定目标函数的唯一执行,因为dict.pop()是一个原子操作。timelord.reset()只要当前计时器尚未启动其线程并弹出该计时器,该计时器就有效_token。这种方法不能完全防止尝试“重置”时新计时器线程的潜在无效启动,但当发生这种情况时,它是一种不重要的冗余,因为目标函数只能执行一次。

此代码在 Python 2 和 3 上运行:

import time
from datetime import datetime
from threading import Timer, current_thread


def f(x):
    print('{} {}: RUNNING TARGET FUNCTION'.format(
        datetime.now(), current_thread().name)
    )
    time.sleep(x)
    print('{} {}: EXITING'.format(datetime.now(), current_thread().name))


class TimeLord:
    """
    Manager Class for threading.Timer instance. Allows "resetting" `interval`
    as long execution of `function` has not started by canceling the old
    and constructing a new timer instance.
    """
    def worker(self, *args, **kwargs):
        try:
            self.__dict__.pop("_token") # dict.pop() is atomic
        except KeyError:
            pass
        else:
            self.func(*args, **kwargs)

    def __init__(self, interval, function, args=None, kwargs=None):
        self.func = function
        self.args = args if args is not None else []
        self.kwargs = kwargs if kwargs is not None else {}
        self._token = True
        self._init_timer(interval)

    def _init_timer(self, interval):
        self._timer = Timer(interval, self.worker, self.args, self.kwargs)
        self._timer.daemon = True

    def start(self):
        self._timer.start()
        print('{} {}: STARTED with `interval={}`'.format(
            datetime.now(), self._timer.name, self._timer.interval)
        )

    def reset(self, interval):
        """Cancel latest timer and start a new one if `_token` is still there.
        """
        print('{} {}: CANCELED'.format(datetime.now(), self._timer.name))
        self._timer.cancel()

        # reduces, but doesn't prevent, occurrences when a new timer
        # gets created which eventually will not succeed in popping
        # the `_token`. That's uncritical redundancy when it happens.
        # Only one thread ever will be able to execute `self.func()`

        if hasattr(self, "_token"):
            self._init_timer(interval)
            self.start()

    def cancel(self):
        self._timer.cancel()

    def join(self, timeout=None):
        self._timer.join(timeout=timeout)

def run_demo(initial_interval):

    print("*** testing with initial interval {} ***".format(initial_interval))
    tl = TimeLord(interval=initial_interval, function=f, args=(10,))
    tl.start()

    print('*** {} sleeping two seconds ***'.format(datetime.now()))
    time.sleep(2)

    tl.reset(interval=6)
    tl.reset(interval=7)
    tl.join()
    print("-" * 70)


if __name__ == '__main__':

    run_demo(initial_interval=5)
    run_demo(initial_interval=2)

示例输出:

*** testing with initial interval 5 ***
2019-06-05 20:58:23.448404 Thread-1: STARTED with `interval=5`
*** 2019-06-05 20:58:23.448428 sleeping two seconds ***
2019-06-05 20:58:25.450483 Thread-1: CANCELED
2019-06-05 20:58:25.450899 Thread-2: STARTED with `interval=6`
2019-06-05 20:58:25.450955 Thread-2: CANCELED
2019-06-05 20:58:25.451496 Thread-3: STARTED with `interval=7`
2019-06-05 20:58:32.451592 Thread-3: RUNNING TARGET FUNCTION
2019-06-05 20:58:42.457527 Thread-3: EXITING
----------------------------------------------------------------------
*** testing with initial interval 2 ***
2019-06-05 20:58:42.457986 Thread-4: STARTED with `interval=2`
*** 2019-06-05 20:58:42.458033 sleeping two seconds ***
2019-06-05 20:58:44.458058 Thread-4: RUNNING TARGET FUNCTION
2019-06-05 20:58:44.459649 Thread-4: CANCELED
2019-06-05 20:58:44.459724 Thread-4: CANCELED
2019-06-05 20:58:54.466342 Thread-4: EXITING
----------------------------------------------------------------------

Process finished with exit code 0

请注意,当interval=2时,两秒后的取消没有效果,因为计时器已经在执行目标函数。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

验证随时间变化的连续条件 的相关文章

随机推荐

  • 没有列名列表的tsql标识插入

    我要将一些数据从一个数据库转储到另一个数据库 我在用 set identity insert MyTable on GO INSERT INTO MyTable SELECT FROM sourceDB dbo MyTable GO set
  • 用整数矩阵对 data.frame 进行子集化

    我一直遇到这个问题 想知道是否有一个简单的解决方法 对于某些情况 我发现考虑将矩阵子集化更合乎逻辑 N lt 12 N NA lt 6 dat lt data frame V1 runif N V2 runif N sel mat lt m
  • C# Random 类的问题

    我有一个代表一枚硬币的类 可以使用 Coin Flip 方法翻转它 Flip 使用 random Next 2 得到代表正面或反面的 0 或 1 这很好用 有点 对于该程序 我需要有 2 个我制作的硬币 比如说 coin1 和 coin2
  • 在 Docker 中运行 Keycloak 时出错

    我试图在 Docker 中运行 Keycloak 但它抛出一个错误 这是泊坞窗文件 FROM jboss keycloak 4 1 0 Final WORKDIR opt jboss keycloak COPY realm export j
  • sklearn pipeline + keras顺序模型-如何获取历史记录?

    Keras https keras io模型 当 fit被调用时 返回一个历史对象 如果我将此模型用作 sklearn 管道的一步 是否可以检索它 顺便说一句 我正在使用 python 3 6 提前致谢 History 回调记录每个时期的训
  • OSX 上的 XAMPP 默认文件夹

    入门手册说我可以将文件放入 Applications XAMPP htdocs 文件夹和 Sites 文件夹中 但是当我将文件放入 Sites 文件夹中时 它会出现以下错误 Server error The server encounter
  • WPF 自定义控件不可见

    当我在 WPF 中创建自定义控件并将其添加到窗口时 我在对话框中看不到任何放置它的内容 这就是我正在做的 创建一个新的 WPF 应用程序 添加 gt 新项目 gt 自定义控件 WPF CustomButton cs 我将 CustomBut
  • 超出 CreateConstantBufferView 处虚拟地址的末尾

    我正在遵循 使用 DirectX12 进行游戏编程 ch 6 代码 但在 ID3DDevice CreateConstantBufferView 中 我发现 D3D12 错误 D3D12 错误 ID3D12Device CreateCons
  • 如何在 TextField (SwiftUI) 上添加底线

    I use Rectangle 在 TextField SwiftUI 上添加底部边框 但我想用protocol TextFieldStyle对于 TextField 样式的底线 如 RoundedBorderTextFieldStyle
  • 如何让枚举存储每个条目的额外信息

    我有一组包含相关信息的项目 这些项目是由我 程序员 定义的 用户不需要更改它们 它们永远不需要根据配置进行更改 并且它们唯一可能更改的时间是在我的应用程序的未来版本中 我事先知道这些项目应该有多少 以及它们的确切数据是什么 枚举是一种很棒的
  • Elasticsearch 单个字段的多个分析器

    我使用严格的预定义映射将不同类型的文档存储在单个索引中 它们都有一些字段 例如 body 但我希望在索引时对它们进行稍微不同的分析 例如 对特定文档使用不同的标记过滤器 并在搜索时以相同的方式处理 据我所知 分析器不能按文档指定 我还考虑使
  • UIScrollView 滚动时捕捉到位置

    我正在尝试实现一个捕捉到点的滚动视图滚动时 我在这里看到的所有帖子都是关于在用户结束拖动滚动条 之后 捕捉到某个点的 我想让它在拖动过程中折断 到目前为止 我已经用它来停止拖动后的惯性 并且效果很好 func scrollViewWillE
  • 检查一个数字是否是回文数

    我尝试使用以下代码检查一个数字是否是回文 unsigned short digitsof unsigned int x unsigned short n 0 while x x 10 n return n bool ispalindrome
  • 什么是 __ext_vector_type__ 和 simd?

    我正在使用 Apple Metal API 以及所谓的simd图书馆 标题中有这样的代码 typedef attribute ext vector type 3 float vector float3 我很好奇它实际上做了什么以及为什么编译
  • 正则表达式查找 Java 字符串中前 8 位数字的第一次出现

    这是我的字符串20161011 我想得到第一个字符串20161011 我正在使用 s 0 9 s 但是它不起作用 有人可以建议正确的用法吗 顺便说一句 我想检索的第一个字符串是格式的日期yyyymmdd 我不需要验证日期格式 因为它已经过预
  • 绕过外键约束强制删除mysql

    我试图从数据库中删除除一个表之外的所有表 最终出现以下错误 无法删除或更新父行 外键约束失败 当然 我可以反复试验来看看这些关键约束是什么 并最终删除所有表 但我想知道是否有一种快速方法来强制删除所有表 因为我将能够重新插入那些我想要的表
  • 使用 PushStreamContent 从 HTTPClient 上传

    我想将大量数据上传到网络服务器from客户端机器 我直接跳到 PushStreamContent 这样我就可以直接写入流 因为结果的大小各不相同 并且可能相当大 流程如下 User runs query gt Reader Ready Ev
  • Jquery 单击功能不适用于动态元素

    我在用 each使用每个数组对象创建按钮 我还尝试给每个按钮一个特定的 id 这样我就可以执行单击事件以进一步编码 但现在我不知道为什么所有按钮都不起作用 我错过了一些代码吗 var questlist startdate 2015 01
  • dmlc 在不使用 #if 的情况下抛出“未知标识符”

    为什么我在fail test1 模板中收到未知标识符错误 而在pass test1 中却没有 template pass test1 param len 10 if true saved int8 data len group pass i
  • 验证随时间变化的连续条件

    我想开发一个Python程序 从某个时刻开始 等待60秒再执行操作 该程序必须具有的另一个功能是 如果我更新初始时间 它必须开始检查条件 我想过用线程来做 但我不知道如何停止线程并以新的开始时间重新启动它 import thread imp