Schedule - Run a job until a certain time Python - python

Hello and thank you in advance. I am trying to write simple code to run a function for a specified duration. I basically copied this verbatim from schedule module docs (just changed units) but for some reason cannot get it to work.
import schedule
from datetime import datetime, timedelta, time
def job():
print('Hello World')
schedule.every(5).seconds.until(timedelta(seconds=20)).do(job)
I am not getting any errors, but the console will not print 'Hello World'. It has to be something simple but I cannot figure it out as I am very new at this.

When using schedule, you will need a while loop to keep the program running. Modify your code like this will solve the issue.
import schedule
from datetime import datetime, timedelta, time
import time
def job():
print('Hello World')
schedule.every(5).seconds.until(timedelta(seconds=20)).do(job)
while True:
schedule.run_pending()
time.sleep(1)

Related

Python Schedule library for scheduling whole script

How can I schedule a whole script using schedule library in Python, not just a function.
Like if i am writing something like
import schedule
from datetime import time,timedelta,datetime
import time as tm
from time import sleep
def mis_mes():
print('Hello')
schedule.every().second.do(mis_mes)
while True:
schedule.run_pending()
tm.sleep(1)
Then it works very well, but only with a single function and, as I said, I want to schedule the whole script.

Can the schedule program execute on specific seconds?

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.

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)

Scheduling a job in Python

I wish to schedule a python script for every 30 minutes. I am currently using the Timer to run the python script but it is not working precisely. I am using Linux. This code works fine on windows but is not working correctly on Linux. It should be triggered after half an hour but it gets triggered within a minute.
from datetime import datetime, timedelta
from threading import Timer
j=1
while True :
x=datetime.today()
y = x + timedelta(minutes=10*j)
print(y)
delta_t=y-x
secs=delta_t.seconds + 1
def hello_world():
print ("hello world")
print("yes)")
t = Timer(secs, hello_world)
t.start()
j=j+1`
Can anyone point out the mistake in above code or suggest an alternative to run the python script in linux after every 30 minutes?
Thank you
You could use Python’s schedule library.
import schedule
def hello_world():
print ("hello world")
print("yes)")
schedule.every(30).minutes.do(hello_world)
while True:
# Checks whether a scheduled task
# is pending to run or not
schedule.run_pending()
Further information: https://www.geeksforgeeks.org/python-schedule-library/

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