Python schedule not running as scheduled - python

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()

Related

Python Scheduler not running at the specified time

I have a job to schedule every day at particular time (let's say 11 am). I am using this code to do that. But it is not executing the job at specified time. If I try to execute it after every 4 or 5 seconds, it works. Does anyone know why it is not working when I am specifying a certain time to execute it? Here is the code that I am using.
import schedule
import time
def show_it():
print('hello')
schedule.every().day.at("11:00").do(show_it)
while 1:
schedule.run_pending()
time.sleep(1)

Schedule a Job every minute on the exact minute during specific times using Python Schedule Library?

I am using the Python Schedule Library and I have been using the following line of code to schedule a job to run every minute, on the exact minute regardless what time the program is started. For instance, if the program is ran at 13:51:30, rather than starting one minute after that time which would be 13:52:30, it will start at 13:52:00.
This is the line of code used to achieve this:
schedule.every(1).minutes.at(":00").do(job)
Now, how can I get schedule to do this between specific times? For instance, if I want this schedule to occur during 10:00 till 11:00?
I hope I understood the question correctly. I use this:
def func():
now_datetime = datetime.now()
if (now_datetime.hour >= 10) & (now_datetime.hour < 11) :
print(now_datetime)
def main():
while True:
schedule.every().minute.at(':00').do(func)
while True:
schedule.run_pending()
time.sleep(1)

It seems misfire_grace_time does not work

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.

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.

Timed method in Python

How do I have a part of python script(only a method, the whole script runs in 24/7) run everyday at a set-time, exactly at every 20th minutes? Like 12:20, 12:40, 13:00 in every hour.
I can not use cron, I tried periodic execution but that is not as accurate as I would... It depends from the script starting time.
Module schedule may be useful for this. See answer to
How do I get a Cron like scheduler in Python? for details.
You can either put calling this method in a loop, which would sleep for some time
from time import sleep
while True:
sleep(1200)
my_function()
and be triggered once in a while, you could use datetime to compare current timestamp and set next executions.
import datetime
function_executed = False
trigger_time = datetime.datetime.now()
def set_trigger_time():
global function executed = False
return datetime.datetime.now() + datetime.timedelta(minutes=20)
while True:
if function_executed:
triggertime = set_trigger_time()
if datetime.datetime.now() == triggertime:
function_executed = True
my_function()
I think however making a system call the script would be a nicer solution.
Use for example redis for that and rq-scheduler package. You can schedule tasks with specific time. So you can run first script, save to the variable starting time, calculate starting time + 20 mins and if your current script will end, at the end you will push another, the same task with proper time.

Categories