如何让脚本一次安排大量任务?

时间:2018-01-25 16:09:32

标签: python arrays list datetime scheduled-tasks

我正在尝试编写一个脚本,该脚本将安排在特定时间执行一系列任务。我有大量的任务要安排并且它们一直在变化,所以实现它的唯一现实方法是循环。 到目前为止,我有:

for i in range(len(timetable)):
    try:
        h = int(timetable[i].split(":")[0])+7
        m = int(timetable[i].split(":")[1])-7
        if m < 0:
            h = h -1
            m = m +60
        schedule.every(1).day.at(str(h)+":"+str(m)).do(execute(i))
    except:
        pass

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

我的问题是,当我运行这段代码而不是将任务安排到指定的时间时,它只是连续运行它们。

感谢。

1 个答案:

答案 0 :(得分:0)

问题是你不应该像do(execute(i)) # f() will execute your f function rather than schedule them那样执行你的任务。您应该将任务定义为不同的功能,并仅在调度期间调用其名称。

例如:

# Task 1 
def task1():
    ...

# Task 2
def task2():
    ...

# Task 3
def task3():
    ...

然后将它们安排为

schedule.every(1).day.at(str(h)+":"+str(m)).do(task1)
schedule.every(1).day.at(str(h)+":"+str(m)).do(task2)
schedule.every(1).day.at(str(h)+":"+str(m)).do(task3)

不是

schedule.every(1).day.at(str(h)+":"+str(m)).do(task1()) # this will execute your task

如果你想使用循环,在另一个关于索引号i的函数中定义你的任务函数,并让该函数返回你的任务函数,例如

def taski(i): # indexed function, which return a function
    def task():
        ... # content of your task function
        return ... # return of your task function 
    return task # the return of your index function taski should be your task function, again only name here, no ()

然后使用i

调用索引函数在循环内部进行调度
schedule.every(1).day.at(str(h)+":"+str(m)).do(taski(i))
# now taski(i) will not execute your task, 
# since it returns 'task' which is another function without execution