It seems misfire_grace_time does not work - python

The code I am running is as follows.
scheduler = BackgroundScheduler()
trigger = CronTrigger(day_of_week='0-6', hour=9, minute=12, second='0')
def job2():
print('job2')
scheduler.add_job(func=job2, trigger=trigger, misfire_grace_time=120, id='task_two')
scheduler.start()
while True:
print(datetime.datetime.now())
time.sleep(5)
The output of the program is as follows:
Why job2 function is not executed?
The current time is 09:12, and this time is within 120 seconds after the time specified by the scheduler.

The important line is this:
Next wakeup is due at 2020-02-22 09:12:00+0800 (in 86368.007853 seconds)
It seems that your local time was already past the daily scheduled time of 09:12:00, so the job was scheduled to be run on the next day. That's why you're not seeing it being executed. I don't know why but you seem to be under impression that the trigger will produce a fire time in the past as long as it's within misfire_grace_time of the current time. This is not how it works.

Related

How to create a thread to run a schedule in the background using Python

I would like to use the schedule library in to order to run a filename.py every day at the same time (17:00). I would like to run this schedule in the background. The example given in the documentation with my own criteria is as follows:
import threading
import time
import schedule
def run_continuously(interval=1):
"""Continuously run, while executing pending jobs at each
elapsed time interval.
#return cease_continuous_run: threading. Event which can
be set to cease continuous run. Please note that it is
*intended behavior that run_continuously() does not run
missed jobs*. For example, if you've registered a job that
should run every minute and you set a continuous run
interval of one hour then your job won't be run 60 times
at each interval but only once.
"""
cease_continuous_run = threading.Event()
class ScheduleThread(threading.Thread):
#classmethod
def run(cls):
while not cease_continuous_run.is_set():
schedule.run_pending()
time.sleep(interval)
continuous_thread = ScheduleThread()
continuous_thread.start()
return cease_continuous_run
def background_job():
exec(open('/Users/filename.py').read())
schedule.every().day.at("17:00").do(background_job)
# Start the background thread
stop_run_continuously = run_continuously()
# Do some other things...
time.sleep(10)
# Stop the background thread
stop_run_continuously.set()
However, when I run this code nothing seems to happen for me. I'm unsure what values to put in the interval= and time.sleep() to suit my need. I would be very grateful if someone could clarify this for me.

Python schedule not running as scheduled

I am using below code to excute a python script every 5 minutes but when it executes next time its not excecuting at excact time as before.
example if i am executing it at exact 9:00:00 AM, next time it executes at 9:05:25 AM and next time 9:10:45 AM. as i run the python script every 5 minutes for long time its not able to record at exact time.
import schedule
import time
from datetime import datetime
# Functions setup
def geeks():
print("Shaurya says Geeksforgeeks")
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
# Task scheduling
# After every 10mins geeks() is called.
schedule.every(2).minutes.do(geeks)
# Loop so that the scheduling task
# keeps on running all time.
while True:
# Checks whether a scheduled task
# is pending to run or not
schedule.run_pending()
time.sleep(1)
Is there any easy fix for this so that the script runs exactly at 5 minutes next time.
please don't suggest me to use crontab as I have tried crontabs ut not working for me.
I am using python script in different os
your geeks function will cost time to execute,and schedule job start calculate 5min after geeks done,that's why long time its not able to record at exact time.
if you want your function run at exact time,you can trying this:
# After every 10mins geeks() is called.
#schedule.every(2).minutes.do(geeks)
for _ in range(0,60,5):
schedule.every().hour.at(":"+str(_).zfill(2)).do(geeks)
# Loop so that the scheduling task
It's because schedule does not account for the time it takes for the job function to execute. Use ischedule instead. The following would work for your task.
import ischedule
ischedule.schedule(geeks, interval=2*60)
ischedule.run_loop()

schedule a python script to run every hour

I am trying to write a script that executes every hour
but, when I run it... it takes an hour to run the job for the first time and then, it starts running like every 5 seconds
I don't understand what am I doing wrong here
from apscheduler.schedulers.blocking import BlockingScheduler
def job():
print('excuting job')
scheduler = BlockingScheduler()
scheduler.add_job(job, 'interval', hours = 1)
scheduler.start()
this is another code that I have used, but it's the same result
schedule.every().hour.do(job)
while True:
schedule.run_pending()
time.sleep(20)
Don't do it in python.
Make a file called exehour.bat with this (assuming you're using Windows):
#echo off
cd DIRECTORY-OF-FILE
:loop
timeout 3600
FILE-NAME
goto loop
So this will execute a file every 1 hour when you run it
Or if you need it in python
import time
def runhour():
#YOUR PYTHON CODE GOES UNDERNEATH HERE
#
time.sleep(3600)
Might have something to do within your def, like a rogue brake or other bad while loop or sleep timer. Maybe the checking job timer not being short enough is affecting something as well?
import schedule # I'm not sure about the BlockingScheduler import but this one works for me
import time # Hate how we need an import for this and it's not built into python....
def job():
print('executing job')
# Run your job on first boot without the scheduler
job()
# Then setup the schedule to be used from now on
schedule.every().hour.do(job)
# Check every second if we can do our job yet or not
# Bonus heartbeat . so you know the while loop is running and not crashed.
while True:
schedule.run_pending()
print(".", end="", flush=True)
time.sleep(1) # seconds
If it runs our job() then gets stuck, boot loops or crashes then its in your job def.
if it runs fine the first time, sets up the schedule fine but then gets stuck with executing the schedule then I don't really have any ideas without seeing more of the job() def..
for shits and giggles you could pip uninstall and reinstall schedule again and see if that helps idk..

How to schedule a python function to run every hour at specific minute (ex 00, 10, 20) with apscheduler

I try to schedule a function within my script to run at a specific minute every hour, i.e. if my script starts running at 11.46 my function to run at 11.50, 12.00, 12.10 etc and to do the same thing if it fails and restarts. I have seen that it is possible to do this with cron from command line but is there a way to do it while the script is running with a scheduler?
I have already created a scheduler which runs every 10 minutes after my script starts, but I want my function to run on specific minutes not just specific intervals.
from apscheduler.schedulers.background import BackgroundScheduler
import atexit
def demo_job:
print("test")
try:
sched = BackgroundScheduler(daemon=True)
sched.add_job(demo_job, trigger='interval', minutes=10)
sched.start()
atexit.register(lambda: sched.shutdown(wait=False))
except:
print("Unexpected error:")
If my script starts running at 11.47 the first scheduled call of my function is at 11.57, the next at 12.07, 12.17 etc... I want the first run to be at 12.00, the next at 12.10, 12.20 etc
You can try using the cron trigger.
sched.add_job(
demo_job,
trigger='cron',
minute='*/10',
hour='*'
)
The expression */10 will fire the job at every tenth minute, starting from the minimum value. Crontab ref

python how to run a function everyday at specific time, but can also be terminated

I'm new to explore how to do this in python. What I want to do is run a function every business day at a specific time, e.g., say at 14:55, just 5 minutes before the stock market closes in China. This function will pull some data from a stock market data feeding API and do some simple calculations to generate a signal(-1 means to short, +1 means to long, 0 means don't do anything). I'm not sending the signal yet to make a trade now. I'm just saving the signals everyday to a file locally. Thus, I might be able to collect the signals for 2 weeks or any time I feel like to stop this scheduler.
I notice that APScheduler module being suggested quite often. But I tried it, didn't find a way to make the scheduler stop running 2 weeks after. I only find ways to set up a scheduler to run, maybe every 10 minutes, but it will just keep running a specified function every 10 minutes and can't be stopped programmally, but only through pressing Ctrl+C? For example, I want to run a function every 10 minutes for 6 times, in APScheduler, I didn't see anyway to specify the '6 times' argument. Or I want to run a function every 10 minutes until 1 hour later. I didn't see the '1 hour later' or 'at 16:30' argument either. How to do it?
Currently, I'm doing it this way:
def test_timer():
'''
Uses datetime module.
'''
running = 1
stop_time = datetime.now() + timedelta(seconds=60)
while running:
print('I\'m working...')
time.sleep(5)
running = datetime.now() < stop_time
print('Goodbye!')
Edited: I'm using python 3.6 in Windows 10.
Try this example
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
def job_function():
print("Hello World")
sched = BackgroundScheduler()
# Schedule job_function to be called every 1 second
# FIXME: Do not forget to change end_date to actual date
sched.add_job(job_function, 'interval', seconds=1, end_date="2017-09-08 12:22:20")
sched.start()
Update #1
from apscheduler.schedulers.background import BackgroundScheduler
def job_function():
print("Hello World")
# Here, you can generate your needed days
dates = ["2017-09-08 13:30:20", "2017-09-08 13:31:20", "2017-09-08 13:32:20"]
sched = BackgroundScheduler()
for date in dates:
sched.add_job(job_function, "date", next_run_time=date)
sched.start()
Looks like a problem for crontab in Linux or Task Scheduler in Windows.

Categories