You are using a timezone when configuring the scheduler: scheduler.configure(timezone=pytz.timezone('Asia/Shanghai'))
but you are not using timezone when specifying the next_run_time:
BackgroundScheduler(next_run_time=datetime.now)
Please use timezone in both places. By the way I would use next_run_time on the job, like Alex has suggested, his answer with the timezone would be:
scheduler.add_job(test, 'interval', seconds=30, id='my_job_id',
next_run_time=datetime.now(pytz.timezone('Asia/Shanghai')))
I have also fallen into this timezone problem, because I have used APScheduler code from documentation (https://apscheduler.readthedocs.io/en/3.x/userguide.html) where they set the timezone to pytz.utc:
scheduler = BackgroundScheduler(jobstores=job_stores, executors=executors, job_defaults=job_defaults, timezone=pytz.utc)
(notice timezone=pytz.utc
in the end of the line above)
This is why for me datetime.now()
did not work and I had to use datetime.now(pytz.utc)
I had to use either datetime.utcnow()
or better datetime.now(pytz.utc)
(according to How do I get a value of datetime.today() in Python that is "timezone aware"?)
So now my full code looks like:
scheduler.add_job(my_function, trigger="interval", hours=6, args=[my_argument], id="my_id", next_run_time=datetime.now(pytz.utc))
(notice datetime.now(pytz.utc)
in the end of the line above)