When using APScheduler package in Python, I want to run the scheduled job right after I start the scheduler. How can I do it properly?
next_run_time
param in add_job
method#
In the scheduler, its add_job
1 method has a parameter next_run_time
.
If we specify now time as the value, the job will run immediately.
from datetime import datetime
import time
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
def my_job():
print("job running at ", datetime.now())
trigger = IntervalTrigger(seconds=5)
scheduler = BackgroundScheduler()
scheduler.add_job(
func=my_job,
trigger=trigger
)
scheduler.start()
while True:
time.sleep(2)
If we run the program, the scheduled job should run immediately.
start_date
in IntervalTrigger#
In the interval trigger itself, it has a parameter start_date
to specify when the job run should be triggered.
The time can be a past datetime based doc:
If the start date is in the past, the trigger will not fire many times retroactively but instead calculates the next run time from the current time, based on the past start time.
Can we manipulate the start_date
parameter to make the job run immediately? Sort of.
We can use a past time and let the next run be right after we run the program.
import datetime
import time
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
def my_job():
print("hello, job run at %s", datetime.datetime.now())
amount = 5
eps = 0.01
my_trigger = IntervalTrigger(
seconds=amount,
start_date=datetime.datetime.now() - datetime.timedelta(seconds=amount - eps),
)
scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(
func=my_job,
trigger=my_trigger,
)
print("current time:", datetime.datetime.now())
while True:
time.sleep(2)
In the above code, we try to set start_date
to a past time.
The eps
variable is used to fine-tuning the time.
If I set it to very small value like 0.01, it works.
However, if I set it to 0.0, it does not work, the job will run after amount
time.
So this is not a reliable way to run the job right after we launch the program.
ref#
- interval trigger: https://apscheduler.readthedocs.io/en/3.x/modules/triggers/interval.html