gpt4 book ai didi

python apscheduler,运行作业的更简单方法?

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:39 26 4
gpt4 key购买 nike

我通过 apscheduler 安排了作业。到目前为止,我有 3 份工作,但很快就会有更多。我正在寻找一种方法来扩展我的代码。

目前,每个作业都是它自己的.py文件,在该文件中,我将脚本变成了一个以run()作为函数名的函数。这是我的代码。

from apscheduler.scheduler import Scheduler
import logging

import job1
import job2
import job3

logging.basicConfig()
sched = Scheduler()

@sched.cron_schedule(day_of_week='mon-sun', hour=7)

def runjobs():
job1.run()
job2.run()
job3.run()

sched.start()

这行得通,现在的代码很愚蠢,但它完成了工作。但是当我有 50 个工作时,代码会很笨。如何扩展它?

注意:作业的实际名称是任意的,不遵循某种模式。该文件的名称是 scheduler.py,我在 python shell 中使用 execfile('scheduler.py') 运行它。

最佳答案

import urllib
import threading
import datetime

pages = ['http://google.com', 'http://yahoo.com', 'http://msn.com']

#------------------------------------------------------------------------------
# Getting the pages WITHOUT threads
#------------------------------------------------------------------------------
def job(url):
response = urllib.urlopen(url)
html = response.read()

def runjobs():
for page in pages:
job(page)

start = datetime.datetime.now()
runjobs()
end = datetime.datetime.now()

print "jobs run in {} microseconds WITHOUT threads" \
.format((end - start).microseconds)

#------------------------------------------------------------------------------
# Getting the pages WITH threads
#------------------------------------------------------------------------------
def job(url):
response = urllib.urlopen(url)
html = response.read()

def runjobs():
threads = []
for page in pages:
t = threading.Thread(target=job, args=(page,))
t.start()
threads.append(t)

for t in threads:
t.join()

start = datetime.datetime.now()
runjobs()
end = datetime.datetime.now()

print "jobs run in {} microsecond WITH threads" \
.format((end - start).microseconds)

关于python apscheduler,运行作业的更简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23184410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com