python apschedule BlockingScheduler with interval trigger: Start immediately
Asked Answered
A

3

16

I am using python apscheduler to schedule a specific task every 45 minutes. The problem is, when i add the job and start the scheduler, it starts at 45 minutes from now.

from apscheduler.schedulers.blocking import BlockingScheduler

class myClass:

    def schedule(self):
        self.scheduler = BlockingScheduler()
        self.scheduler.add_job(self.myJob, 'interval', minutes=45)
        self.scheduler.start()

    def myJob(self):
        print('I finally started')

I tried setting start_date, but with no success. How can i make sure the job is executed immediately, and not after waiting the interval for the first time?

Audible answered 6/4, 2017 at 11:56 Comment(2)
The design of the interval trigger has been fixed in the upcoming v4.0 release so that the first run starts immediately.Soidisant
ahh! long overdue ty. Not realeased yet though.Callis
B
34

Try next_run_time=datetime.now().

Blond answered 7/4, 2017 at 11:34 Comment(1)
from datetime import datetime, then I use datetime.utcnow() because I set up my scheduler with BlockingScheduler({'apscheduler.timezone': 'UTC'})Exhortative
Q
6

Not a good solution but works for me.

from apscheduler.schedulers.blocking import BlockingScheduler

class myClass:

    def schedule(self):
        self.myJob()#run your job immediately here, then scheduler
        self.scheduler = BlockingScheduler()
        self.scheduler.add_job(self.myJob, 'interval', minutes=45)
        self.scheduler.start()

    def myJob(self):
        print('I finally started')
Quattlebaum answered 9/4, 2018 at 1:32 Comment(0)
K
1

The given answers are too complex for a simple task that is well documented: https://apscheduler.readthedocs.io/en/3.x/modules/triggers/date.html#examples

To add a job to be run immediately:

The 'date' trigger and datetime.now() as run_date are implicit

sched.add_job(my_job)
Kathlenekathlin answered 20/1, 2022 at 10:34 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.