python schedule recurring event given only time in am/pm format - python

I am trying to to set a recurring event (running a python script) at a set time (9am EST, US in this case). The only way I found to do this was to manually calculate the miliseconds for the first time and increment them by 24 hours to schedule the next day. Is there a better way?
#!/usr/bin/python
import sched
import time
time_in_ms=???
scheduler = sched.scheduler(time.time, time.sleep)
def my_event(name):
import room_light.py
print 'START:', time.time()
scheduler.enterabs(time_in_ms, 1, my_event, ('',))
scheduler.run()

You can just use cron jobs. This is the best way to schedule tasks.
Update:
it's an OS feature, not Python.

Related

Repeat python function at every system clock minute

I've seen that I can repeat a function with python every x seconds by using a event loop library in this post:
import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc):
print("Doing stuff...")
# do your stuff
s.enter(60, 1, do_something, (sc,))
s.enter(60, 1, do_something, (s,))
s.run()
But I need something slightly different: I need that the function will be called at every system clock minute: at 11:44:00PM, 11:45:00PM and so on.
How can I achieve this result?
Use schedule.
import schedule
import time
schedule.every().minute.at(':00').do(do_something, sc)
while True:
schedule.run_pending()
time.sleep(.1)
If do_something takes more than a minute, threadidize it before passing it to do.
import threading
def do_something_threaded(sc):
threading.Thread(target=do_something, args=(sc,)).start()
Exactly 0 is very hard to accomplish (since there is always a small delay) but You can check if the minute has changed:
import datetime
minute = None
while True:
if datetime.datetime.now().minute != minute:
print(f'Do something {datetime.datetime.now()}')
minute = datetime.datetime.now().minute
result at my mahcine:
Do something 2022-01-21 11:24:39.393919
Do something 2022-01-21 11:25:00.000208
So it checks if there is a new minute and calls again the datetime function. The delay is around 0.2 milliseconds.
If you think along the lines of a forever running program, you have to ping the system time using something like now = datetime.now(). Now if you want 1 sec accuracy to catch that :00 window, that means you have to ping a lot more often.
Usually a better way is to schedule the script execution outside using Windows Task Scheduler or Crontab in Linux systems.
For example, this should run every XX:YY:00:
* * * * * python run_script.py

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

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.

Trigger a Python function exactly on the minute

I have a function that I want to trigger at every turn of the minute — at 00 seconds. It fires off a packet over the air to a dumb display that will be mounted on the wall.
I know I can brute force it with a while loop but that seems a bit harsh.
I have tried using sched but that ends up adding a second every minute.
What are my options?
You might try APScheduler, a cron-style scheduler module for Python.
From their examples:
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.start()
def job_function():
print "Hello World"
sched.add_cron_job(job_function, second=0)
will run job_function every minute.
What if you measured how long it took your code to execute, and subtracted that from a sleep time of 60?
import time
while True:
timeBegin = time.time()
CODE(.....)
timeEnd = time.time()
timeElapsed = timeEnd - timeBegin
time.sleep(60-timeElapsed)
The simplest solution would be to register a timeout with the operating system to expire when you want it to.
Now there are quite a few ways to do so with a blocking instruction and the best option depends on your implementation. Simplest way would be to use time.sleep():
import time
current_time = time.time()
time_to_sleep = 60 - (current_time % 60)
time.sleep(time_to_sleep)
This way you take the current time and calculate the amount of time you need to sleep (in seconds). Not millisecond accurate but close enough.
APScheduler is the correct approach. The syntax has changed since the original answer, however.
As of APScheduler 3.3.1:
def fn():
print("Hello, world")
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(fn, trigger='cron', second=0)
You can try Threading.Timer
See this Example
from threading import Timer
def job_function():
Timer(60, job_function).start ()
print("Running job_funtion")
It will print "Running job_function" every Minute
Edit:
If we are critical about the time at which it should run
from threading import Timer
from time import time
def job_function():
Timer(int(time()/60)*60+60 - time(), job_function).start ()
print("Running job_funtion")
It will run exactly at 0th second of every minute.
The syntax has been changed, so in APScheduler of version 3.6.3 (Released: Nov 5, 2019) use the following snippet:
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
def fn():
print('Hello, world!')
sched = BlockingScheduler()
# Execute fn() at the start of each minute.
sched.add_job(fn, trigger=CronTrigger(second=00))
sched.start()
The Python time module is usually what I use for events like this. It has a method called sleep(t), where t equals the time in seconds you want to delay.
Combined with a while loop, you can get what you're looking for:
import time
while condition:
time.sleep(60)
f(x)
May use this example:
def do():
print("do do bi do")
while True:
alert_minutes= [15,30,45,0]
now=time.localtime(time.time())
if now.tm_min in alert_minutes:
do()
time.sleep(60)
you could use a while loop and sleep to not eat up the processor too much

Categories