【问题标题】:Execute a function every certain time without counting the time of execution of the function [duplicate]每隔一定时间执行一个函数,而不计算函数的执行时间[重复]
【发布时间】:2016-11-15 17:50:36
【问题描述】:

我需要从特定时间开始每隔一定时间间隔执行一个函数。

例如,如果开始时间是 00:00:00,间隔是 5 秒,那么我需要这个函数的执行时间是:

00:00:00
00:00:05
00:00:10
00:00:15
...
23:59:55

如你所见,我的意思是系统的时钟

在stackoverflow中存在许多与此问题相关的问题,例如 How to execute a function asynchronously every 60 seconds in Python?What is the best way to repeatedly execute a function every x seconds in Python?.Futhermore 我看到了 schedule 0.3.2 的其他解决方案。

我的问题是,例如使用以下代码:

import schedule
import time

def job():
    print("I'm working...")
    print 'execute f time: ', time.ctime(time.time())
    print 'execute f time: ', time.time()
schedule.every().minutes.do(job)

while 1:
    schedule.run_pending()
    time.sleep(1)

在这种情况下,当我运行我的代码时,我的代码输出是:

I'm working...
execute f time:  Wed Jul 13 04:32:00 2016
execute f time:  1468398720.88
I'm working...
execute f time:  Wed Jul 13 04:33:00 2016
execute f time:  1468398780.94
I'm working...
execute f time:  Wed Jul 13 04:34:01 2016
execute f time:  1468398841.0

正如你所看到的,这段代码每分钟执行一次,但是间隔从 1 分钟变为 1 分钟 1 秒,这个错误对我来说很重要,可能是函数打印时间的原因。在这种情况下,我需要每分钟继续执行一次,而不需要由函数 print 的时间累积和引起的秒数

我的计时器解决方案有同样的错误:

import threading
import time

def f():
    # call f() again in 10 seconds
    threading.Timer(10, f).start()
    # do something here ...
    print 'execute f time: ', time.time()
    time.sleep(5)

# start calling f now and every 10 sec thereafter
print 'init time: ', time.time()
f()

输出的片段显示,某个时刻的计算错误导致间隔大于 5 ([0, 5, 10,16,21,26,....]),这对我来说是错误的,因为对我来说执行函数的时间很重要:

init time:  1468407868.6
execute f time:  1468407868.6
execute f time:  1468407878.6
execute f time:  1468407888.6
execute f time:  1468407898.6
execute f time:  1468407908.61  # change the interval
execute f time:  1468407918.61
execute f time:  1468407928.61

使用 sched 模块我有同样的问题

请多多指教 提前致谢。

更新

好的,我测试了 crontab,但不满意。首先我在Ubuntu中测试我的用户的配置crontab文件,但后来我找到了一个库来写指令到他的crontab文件配置,所以我使用库Crontab

#!/usr/bin/python
# -*- coding: utf-8 -*-

from crontab import CronTab
task = CronTab(user='cyberguille')
command='/home/cyberguille/date.py'
cron_job=task.new(command)
cron_job.setall('*/1, *, *, *, *')
task.write()
print task.render()

你可以看到每一分钟执行一次代码,但是我看到两个问题,在不到一分钟内执行并不容易(见How to run scripts every 5 seconds using cron?)而且我不知道为什么当我每一分钟执行一次时一分一秒,我们有太多的计算和错误,但这个错误比上面的例子更适合

date.py 中的代码是这样的

#!/usr/bin/python
# -*- coding: utf-8 -*-

#import time
from datetime import datetime
tiempo = datetime.now()
#tiempo = time.strftime("%H:%M:%S")
archivo=open('/home/cyberguille/archivo_fecha.txt', 'a+')

archivo.write(str(tiempo) + '\n')

输出的一个片段是

2016-07-19 00:11:01.307779
2016-07-19 00:12:01.365995
2016-07-19 00:13:01.421373
2016-07-19 00:14:01.477752
2016-07-19 00:15:01.532234
2016-07-19 00:16:01.588818
2016-07-19 00:17:01.649581
2016-07-19 00:18:01.705975
2016-07-19 00:19:01.759986
2016-07-19 00:20:01.816754
2016-07-19 00:21:01.873748
2016-07-19 00:22:01.927750
2016-07-19 00:23:01.980666
2016-07-19 00:24:02.036164
2016-07-19 00:25:01.090912
2016-07-19 00:26:01.148098

真的每一分钟你都可以说这不是重要的错误,但为什么不能执行例如 00 中的秒数

2016-07-19 00:11:00.307779
2016-07-19 00:12:00.365995
2016-07-19 00:13:00.421373
2016-07-19 00:14:00.477752

可能脚本调用很慢。

我找到了一个对我来说效果很好的解决方案,这就是脚本

    from multiprocessing import Process
    from datetime import datetime
    import time
    import sched

    def timer(interval):
            sc = sched.scheduler(time.time, time.sleep)
            sc.enter(1, 1, do_something, (sc,interval))
            sc.run()
     def do_something(sc,interval):
            dateTime = datetime.now()
            if(dateTime.second%interval==0):
                p = Process(target=SensorContainer.run,args=(dateTime,))
                p.start()
            sc.enter(1, 1, SensorContainer.do_something, (sc,interval,))


     def run(datetime):
            print datetime

使用此解决方案,计时器在 0 秒内每分钟工作一次,正如您所看到的,我的度量是当我调用该函数时,这与 crontab 中的不同,但无论如何我测试在运行函数中花费时间an 也是 0 秒。

【问题讨论】:

    标签: python timer scheduled-tasks


    【解决方案1】:

    我相信你最好依靠操作系统来进行调度而不是 Python。拥有一个具有单一功能的简单脚本,然后使用 crontab(如果使用 Linux)或 Windows 任务计划程序来安排执行会更简单。

    更喜欢 OS 方法的原因之一是稳健性。例如,如果您依赖 Python 进行调度,如果发生未处理的异常,那么您的脚本将终止,直到它再次手动执行。系统重启等也是如此。

    如果您使用操作系统进行调度,即使在系统重新启动和未处理的异常的情况下,脚本也会继续按照预定义的调度执行。

    【讨论】:

    • 我使用linux,也许我可以在Python中执行shell命令来做到这一点,因为这段代码是oython开发的系统的一部分。您能否扩展您对为什么使用操作系统比使用 python 更好的答案?
    • 现在我阅读了有关 crontab 的信息,我很晚才测试你的建议,如果我能尽快为我工作,我会投票并接受你的回答
    • 我通过对您的建议的一项分析更新了我的问题,可能存在其他使用 crontab 的方式,您可以告诉我如何,请给我您的意见。
    猜你喜欢
    • 2021-07-15
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多