我是APScheduler的新手并在更大范围内实施之前对其进行测试。
我已经创建了下面的代码,但是当我将add_job与trigger='date'
一起使用时,我的函数永远不会被调用。如果我使用trigger='interval'
,那么一切正常。
我还尝试使用run_date
param,没有运气。
有什么可能出错的想法吗?
Apscheduler是版本3.0.3
非常感谢提前:)
def my_listener(event):
if event.exception:
print('The job crashed :(')
else:
print('The job worked :)')
def test():
print("{} ok ".format(datetime.now()))
def myFunc(content, img):
print("{} - content={}|image{}".format(datetime.now(), content, img))
myfile = open("scheduler.log", "a")
myfile.write("{} - content={}|image{}".format(datetime.now(), content, img))
myfile.close()
def main():
jobstores = \
{
'default': SQLAlchemyJobStore(url="postgresql+psycopg2://{}:{}@{}:{}/{}".format(db_user, db_password, db_host, db_port, db_database))
}
executors = \
{
'default': ThreadPoolExecutor(20),
'processpool': ProcessPoolExecutor(5)
}
job_defaults = \
{
'coalesce': False,
'max_instances': 3
}
scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)
scheduler.start()
CURR_DATE = datetime.strptime(datetime.strftime(datetime.now(), '%Y%m%d%H%M'), '%Y%m%d%H%M')
JOB_DATE = CURR_DATE + timedelta(minutes=1)
uid=uuid.uuid4()
newjob = scheduler.add_job(myFunc,
trigger='date',
args=['content data', 'image data'],
kwargs=None,
id=str(uid),
name='test' + str(uid),
misfire_grace_time=5,
coalesce=False,
max_instances=1,
next_run_time= JOB_DATE,
jobstore='default',
executor='default',
replace_existing=True)
print("Added - {}".format(newjob))
scheduler.add_listener(my_listener, events.EVENT_JOB_EXECUTED | events.EVENT_JOB_ERROR)
scheduler.print_jobs()
while True:
sys.stdout.write('{}\n'.format(datetime.now())); sys.stdout.flush()
sleep(1)
if __name__ == "__main__":
main()
答案 0 :(得分:3)
问题在于您正在使用 next_run_time = JOB_DATE, 而不是run_date = JOB_DATE,
另一个选项是声明你的触发器并将其作为参数传递给像这样的工作:
trigger = DateTrigger(run_date=start_date)
newjob = scheduler.add_job(myFunc,
trigger=trigger,
args=['content data', 'image data'],
kwargs=None,
id=str(uid),
name='test' + str(uid),
misfire_grace_time=5,
coalesce=False,
max_instances=1,
jobstore='default',
executor='default',
replace_existing=True)
您的代码的另一个问题是,当您使用不知情的日期时间制作调度程序时,
CURR_DATE = datetime.strptime(datetime.strftime(datetime.now(), '%Y%m%d%H%M'), '%Y%m%d%H%M')
JOB_DATE = CURR_DATE + timedelta(minutes=1) #this is unaware
尝试以这种方式宣布您的约会:
import pytz
import datetime
job_date = datetime.datetime.now(pytz.UTC) + datetime.timedelta(minutes=1)