python 计划 - 来自 python 列表的工作

python schedule - jobs from python list

我想使用 python schedule library 来安排大量作业。
所有作业都执行相同的操作,但输入不同。
输入存储在 python 列表中。

想法是将列表中的每个输入放入共享队列,然后按顺序处理每个输入。

这是一个例子和我的尝试:

import queue
import time
import threading
import schedule

def job(name):
    print(name)


def worker_main():
    while 1:
        (job_func,job_msg) = jobqueue.get()
        job_func(job_msg)
        jobqueue.task_done()


name = ['jane', 'alice', 'mary']
jobqueue = queue.Queue()

schedule.every(2).seconds.do(jobqueue.put, (job, name))

worker_thread = threading.Thread(target=worker_main)
worker_thread.start()

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

不幸的是,这种方法 运行 列表中所有项目的 1 个作业。 有人有什么建议吗?谢谢。

每 2 秒打印一次每个名字:

for n in name:
    schedule.every(2).seconds.do(jobqueue.put, (job, n))
[Second 2]: jane
[Second 2]: alice
[Second 2]: mary
[Second 4]: jane
[Second 4]: alice
[Second 4]: mary

每 2 秒打印一个名字并循环遍历列表:

from itertools import cycle
name_iter = cycle(name)
schedule.every(2).seconds.do(lambda: jobqueue.put((job, next(name_iter))))
[Second 2]: jane
[Second 4]: alice
[Second 6]: mary
[Second 8]: jane
[Second 10]: alice
[Second 12]: mary

What if I do not want to use cycle but stop when the iterator has been consumed

看来你可以加注 schedule.CancelJob https://schedule.readthedocs.io/en/stable/examples.html#run-a-job-once

name_iter = iter(name)
def queue_name():
    try:
        jobqueue.put((job, next(name_iter)))
    except StopIteration:
        return schedule.CancelJob

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