Python sched调度程序和重新启动

2024-09-28 15:27:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我读过python sched(任务调度器),它的工作原理类似于cron

但我有一个问题:

  • 比方说,如果我计划每2小时运行一次函数,同时我的系统关闭,然后我再次重新启动系统

调度器是否在2小时后自动启动并运行该功能?还是我必须在关闭系统后再次启动

  • sched是否像守护进程一样工作

Tags: 功能进程系统调度cron计划原理小时
2条回答

这三个问题的答案都是否定的

sched与cron不同。它使用通用计时器或计数器函数和延迟函数,并允许您在特定时间(由通用计时器函数定义的事件)后安排函数调用

它不会在您关闭程序后运行,除非您通过写入文件或数据库来维护状态。这很复杂,使用cron会更好

sched在事件上工作,但不在后台工作。因此,它并不完全是一个deamon,但是您可以使用操作系统工具在后台运行程序来解除它的名字

如果是这样:
即使在系统重新启动后,这也会起作用吗?
答案是:不,那么turbogear调度器如何在cron中使用cronos运行呢?系统重启后,turbogear中的预定事件也将消失。
如果我错了,请纠正我

import time
import sched
import datetime
import threading
import calendar
#from datetime import datetime


class test:

    def __init__(self):
        self.name = ''

    def getSec(self):

        now = datetime.datetime.now()
        print "now - ", now
        currentYear = now.year
        currentMonth = now.month
        currentDay = now.day
        currentHour = now.hour
        currentMinute = now.minute
        currentSecond = now.second
        currentMicroseconds = now.microsecond
        command = "python runbackup.py"
        print "command is - ", command

        print "currentMinute - ", currentMinute
        print "currentSecond - ", currentSecond
        # current time
        a = datetime.datetime(currentYear, currentMonth, currentDay, currentHour, currentMinute, currentSecond, currentMicroseconds)

        last_date_of_current_month = calendar.monthrange(currentYear, currentMonth)[1]
        print "last_date_of_current_month - ", last_date_of_current_month
        b = datetime.datetime(currentYear, currentMonth, int(last_date_of_current_month), 23, 59, 59, 000000)
        #b = datetime.datetime(currentYear, currentMonth, int(29), 18, 29, 00, 000000)
        #print "date time of b is - %s %s " % (18, 29)

        c = b-a
        print "c is - ", c

        time.sleep(1)
        scheduler = sched.scheduler(time.time, time.sleep)
        #scheduler.cancel(e1)
        sec = c.seconds
        print "second -  ", sec
        print "scheduler entered."
        e1 = scheduler.enter(sec, 1, self.getSec, ())
        t = threading.Thread(target=scheduler.run)
        print "thread started."
        print "======================================"
        t.start()

        #scheduler.cancel(e1)
        #print "canceled."

        return True

if __name__=='__main__'  :
    obj = test()
    obj.getSec()

相关问题 更多 >