Can the schedule program execute on specific seconds? - python

I am trying to create a program that can execute on a specific time every day, but I wonder if there's a way to make this program more precise to execute on specific seconds.
import time
import schedule
def func():
print("ok")
schedule.every().day.at("20:55").do(func)
while True:
schedule.run_pending()
time.sleep(1)

Yes, it is pretty simple. You could do something like this:
import schedule
import time
import datetime
def func():
print("Working now")
print(datetime.datetime.now())
schedule.every().day.at("15:50:15").do(func)
while True:
schedule.run_pending()
time.sleep(1)
Your func will be executed each day at 15:50:15, where the last number of course indicates the seconds. You can verify it with the second print inside func.

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

in python, how to pause until certain time only without date in pause library

I have python script and I want it to run at 10AM. I tried using with pause and datetime library like the code below
import pause
import datetime
pause.until(datetime.datetime(2021,1,6,10,00))
that means the script will pause until 6 January 2021 10.00 AM. What I want is, how to pause only certain time only the hour and the minute and seconds without putting the date there? is it possible?
Check out this library. I think it will suit your needs: https://pypi.org/project/schedule/
You can code things like:
import schedule
import time
def job():
print("I'm working...")
schedule.every().day.at("10:30").do(job)
while True:
schedule.run_pending()
time.sleep(1)

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 different tasks at different times in never-ending program

I'll preface this by saying I'm not an advanced programmer and I have only written programs that run sequentially and exit. What I'd like to do now is write a python script that I'll launch and it will run a function every 5 minutes and another function every 10 minutes and do so indefinitely. Here's some pseudo-code:
def RunMeEvery5min:
do something
def RunMeEvery10min:
do something
while True:
every 5 minutes run RunMeEvery5min
every 10 minutes run RunMeEvery10min
do this forever until I kill the program
So is this threading? It really doesn't matter if the tasks line up or not as they're essentially unrelated. I would venture to guess that this is a common type of programming question, but I've never really understood how to accomplish this and I don't even know what to search for. Any helpful examples or links to basic tutorials would be much appreciated!
Thanks!
Maybe this will help you https://github.com/dbader/schedule
import schedule
import time
def job():
print("I'm working...")
schedule.every(10).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
You can use sched from Python standard library.
import sched, time
from datetime import datetime
scheduler = sched.scheduler(time.time, time.sleep)
def execute_every_05mins():
print(datetime.now().strftime("%H:%M:%S"))
scheduler.enter(300, 0, execute_every_05mins, ())
def execute_every_10mins():
print(datetime.now().strftime("%H:%M:%S"))
scheduler.enter(600, 0, execute_every_10mins, ())
if __name__ == "__main__":
scheduler.enter(0, 0, execute_every_05mins, ())
scheduler.enter(0, 0, execute_every_10mins, ())
scheduler.run()

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