【问题标题】:How can I implement this where I print this message every __ seconds __ times?如何在每 __ 秒 __ 次打印此消息的情况下实现这一点?
【发布时间】:2019-11-03 09:27:03
【问题描述】:

我想每隔 __ 秒调用一次 printFunction 方法,但我想在调用一定次数后停止调度。例如,每 5 秒打印 10 次。从另一个文件中提取这些频率和运行时间值。

在 PyCharm 中运行。

进口时间表 进口时间

类示例:

# basic function to print
def printFunction(self):
    print("Hello world")

def repeated(self):
    # reads in two values from another file
    systemFrequency = float(freqSettings.systemFrequency)
    systemRunTime = int(freqSettings.systemRunTime)
    global count 
    count = 0

    while (count < systemRunTime): 
        self.printFunction
        self.increaseCount


 def increaseCount(self):
    global count
    count += 1

【问题讨论】:

  • 问题是......?
  • 当前调用 self 会立即打印“hello world”__ 次,而不是等待一定的秒数

标签: python schedule


【解决方案1】:

调度器运行的函数需要返回CancelJob才能停止被调度。

这是我的实现方式:

import schedule

def my_function():
    print("hello world")

def wrapper():
    wrapper.counter +=1
    my_function()
    if wrapper.counter == 10:
        return schedule.CancelJob
wrapper.counter = 0

schedule.every(1).seconds.do(wrapper)

while True:
    schedule.run_pending()
    print(schedule)

显示 10 个“hello world”

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 2010-11-23
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多