python中以精确的分钟标记计时(类似Cron)作业

python中以精确的分钟标记计时(类似Cron)作业,python,cron,Python,Cron,我想每分钟运行一个进程,问题是我的进程需要大约5秒,因此,如果我计划每分钟运行一次作业,它每次都会被移动5秒 这就是我所拥有的: import schedule def job(): print("Date and time: " + str(datetime.datetime.now()) time.sleep(5) # I only put this here to emulate my 5 second lasting process schedule.every(1

我想每分钟运行一个进程,问题是我的进程需要大约5秒,因此,如果我计划每分钟运行一次作业,它每次都会被移动5秒

这就是我所拥有的:

import schedule

def job():
    print("Date and time: " + str(datetime.datetime.now())
    time.sleep(5) # I only put this here to emulate my 5 second lasting process 

schedule.every(1).minutes.do(job)

while True:
    schedule.run_pending()
    time.sleep(1)
我在另一篇文章中看到了这个解决方案,但我想更好地使用cron作业:

import time

while True:
    now = time.localtime()
    # Do what you need to do
    time.sleep(59 - now.tm_sec) #sleeps until roughly the next minute mark

谢谢

如果您想从Python(而不是通过系统
cron
本身)管理作业,那么我建议查看

例如:

from __future__ import print_function

from time import sleep

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger

once_per_minute = CronTrigger('*', '*', '*', '*', '*', '*', '*', '0')
scheduler = BackgroundScheduler()

scheduler.start()

def my_func():
    print('hello!')

scheduler.add_job(my_func, trigger=once_per_minute)

sleep(180)

你对cron有误解

如果安装此cron作业:

* * * * * /usr/bin/python /path/to/script.py
您可以在脚本中这样做:

import datetime
import time

f = open('/tmp/cron_start_times.txt', 'a')
f.write("{}\n".format(datetime.datetime.now()))
time.sleep(5)

通过查看
/tmp/cron\u start\u times.txt
可以看到脚本是在一分钟的第一秒启动的。正如其他人所说,您会遇到这样一个问题:如果脚本花费的时间超过60秒,它将并行运行2次或更多次。但是如果这不是一个问题,那么您只需要做cron工作就可以了。

您的问题是什么?还有,这个
时间表
模块是什么?它真的和cron有什么关系吗?你看过吗?如果你想让它精确到第二秒,这会变得非常复杂。您需要如此精确的原因是什么?我建议您实际使用cron,而不是尝试用其他调用来模拟它。cron将在指定的时间启动您的作业;你需要做出特殊的规定才能让它不这样做(比如,如果前一个版本还在运行)。我可以用这种方式将python对象从一个过程存储到下一个过程吗?OP实际上并没有使用
cron
,他问的是python脚本中类似“cron”的行为。我以为他问的是cron,正如他所说,我想更好地使用cron作业。但没关系。@Eudald:如果你想在调用之间传递python对象,那么你可以通过pythons pickle/unpickle来实现,但这已经变得很麻烦了。如果您想这样做,最好使用rons解决方案