1

I want my jobs start right now, I know I can use job.modify method to change next_run_time, but many jobs should edit, so I configured the scheduler:

from datetime import datetime

import pytz
from apscheduler.schedulers.background import BackgroundScheduler

scheduler = BackgroundScheduler(next_run_time=datetime.now)

scheduler.configure(timezone=pytz.timezone('Asia/Shanghai'))


def test():
    print('hello', datetime.now())


job = scheduler.add_job(test, 'interval', seconds=30, id='my_job_id')

print(datetime.now())
scheduler.start()

The job doesn't run right now, what shoud I do?

Louie Feng
  • 38
  • 6

2 Answers2

2

You need to pass the current time to scheduler.add_job():

scheduler.add_job(test, 'interval', seconds=30, id='my_job_id',
                  next_run_time=datetime.now())
Alex Grönholm
  • 5,563
  • 29
  • 32
  • Louie is using the pytz.timezone('Asia/Shanghai') timezone, so next_run_time should be in this timezone as well: next_run_timezone=datetime.now(pytz.timezone('Asia/Shanghai')) – mrc Nov 25 '21 at 13:21
0

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)

mrc
  • 126
  • 1
  • 11