python schedule module - not executing - python

Accoring to the documentation the following sample code should execute once, but it does not when including var currentTime , can you tell me how to pass the var to the schedule process properly
import schedule
import time
from datetime import datetime
currentTime = datetime.now().strftime('%H:%M')
def job_that_executes_once():
# Do some work that only needs to happen once...
print ('Only Once')
return schedule.CancelJob
schedule.every().day.at('22:30').do(job_that_executes_once)
while True:
schedule.run_pending()
time.sleep(1)
print ('Not executed')

Related

Python code to schedule a task and to call it every day at a given time

I wrote the following code in Python to perform a function at a particular time everyday. But it's showing the error that "_func1 is missing the parameter 'self'", but when I give the parameter, it's giving the error that 'self' is not defined. Any idea how I can fix it?
import schedule
import time
def _func1(self):
print("func1 is running")
self.wait(150)
print('running cycle mode')
def _func2(self):
print("func2 is running")
print('running cycle mode')
print("mode 2 running")
schedule.every().day.at("14:00").do(_func1)
while True:
schedule.run_pending()
time.sleep(1)
As #MatthiasL mentioned in his answer, getting rid of self does the trick. The following code sample is working:
import time
import schedule
def _func1():
print("func1 is running")
time.sleep(150)
print('running cycle mode')
schedule.every().day.at("11:30").do(_func1)
while True:
schedule.run_pending()
time.sleep(1)

How to get VSCode to run an apscheduler without terminating?

When I click the arrow to run the python code, it simply executes.
However, if I select the option to run the code line-by-line, then the scheduled tasks will continually run as desired.
import datetime
from datetime import datetime, timedelta
import time
from apscheduler.schedulers.background import BackgroundScheduler
sched = BackgroundScheduler(daemon=True)
frequency = 10/60
def main_func(frequency):
start_time = datetime.now()
end_time = start_time + timedelta(minutes=frequency)
print("Start Time: ", start_time)
print("End Time: ", end_time)
if __name__ == "__main__":
sched.add_job(main_func, 'interval', [frequency], minutes=frequency)
sched.start()
(Undesired): Pressing Button in VSCode:
(Desired): Selecting All Code in script within VSCode, Right Clicking and Run Line-by-Line
Questions:
How can I run the python file so it behaves like I ran it line-by-line and doesn't immediately terminate?
Also, will that method work if I ran the python script from a task scheduler?
The answer to this question is is literally the first entry in the APScheduler FAQ.
The essence is that you're starting a background service and then letting the script run to the end which then exits the process. Use cases like these are what BlockingScheduler is for:
from datetime import datetime, timedelta
import time
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
frequency = 10/60
def main_func(frequency):
start_time = datetime.now()
end_time = start_time + timedelta(minutes=frequency)
print("Start Time: ", start_time)
print("End Time: ", end_time)
if __name__ == "__main__":
sched.add_job(main_func, 'interval', [frequency], minutes=frequency)
sched.start()

python apscheduler does nothing

I made the following ,but it doesn't print the time.
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
def tick():
print('Tick! The time is: %s' % datetime.now())
scheduler = BackgroundScheduler()
scheduler.add_job(tick,'interval',seconds=3)
print('starting')
scheduler.start()
print('stopped')
This is because your program is exiting before the interval has elapsed and needs to be kept alive at least until the first interval, consider using the following example:
while True:
#Thread activity here (time.sleep(2) for example)
or using other forms of activity to keep your main thread alive. Or just print out the time without this scheduling if that's what you really need.

How to stop/terminate a python script from running with BackgroundScheduler() of APScheduler

I'm trying to stop the while loop execution from inside the foo() function. I've tried exit() / sys.exit without success. How can I stop completely the execution of the program from inside the function?
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
import time
import sys
def foo(stop = False):
print('Function foo executed')
if stop:
sys.exit
scheduler = BackgroundScheduler()
dd = datetime.now() + timedelta(seconds=10)
scheduler.add_job(foo, 'date', run_date=dd, args=[True])
scheduler.start()
while True:
print('Inside the loop')
time.sleep(2)
Use psutil
import psutil
psutil.Process().terminate()
From the doc,
psutil.Process() If PID is omitted current process PID (os.getpid()) is used.
Be aware terminate will leave with exit code 0. If you want other exit code, you can use send_signal() or even kill()

How to schedule job with a particular time as well as interval?

Using python's schedule module how can I start a job at particular time and thereon it should be scheduled at regular intervals.
Suppose I want to schedule a task every 4 hours starting from 09:00 am.
schedule.every(4).hours.at("09:00").do(task) # This doesn't work
How to achieve the above?
You can convert the inner schedule (every 4 hours) into a separate function which would be called by the main schedule (fixed time). The inner schedule function would be the one calling your job function.
Example -
import schedule
import time
def job():
print "I am working" #your job function
def schedule_every_four_hours():
job() #for the first job to run
schedule.every(4).hour.do(job)
return schedule.CancelJob
schedule.every().day.at("09:00").do(schedule_every_four_hours)
while True:
schedule.run_pending()
time.sleep(1)
If you would like to kill the schedule based on your requirement read more here. Check here.
The above solution will not work if there are multiple schedules, as the schedule.CancelJob will cancel the other schedules on the pipe, better to use clear tag
import schedule
from datetime import datetime
import time
def task():
print 'I am here...',datetime.now()
def schedule_every_four_hours(clear):
if clear =='clear':
schedule.every(2).seconds.do(task).tag('mytask1') #for the first job to runschedule.every(4).hour.at("9:00").do(task)
else:
schedule.every(5).seconds.do(task).tag('mytask2') # for the second job to runschedule.every(4).hour.at("9:00").do(task)
print clear
schedule.clear(clear)
now = datetime.now()
times = str(now.hour+0)+ ":"+str(now.minute+1)
times1 = str(now.hour+0)+ ":"+str(now.minute+3)
schedule.every().day.at(times).do(schedule_every_four_hours,'clear').tag('clear')
schedule.every().day.at(times1).do(schedule_every_four_hours,'clear1').tag('clear1')
while True:
schedule.run_pending()
time.sleep(1)
Just as add on - because I was searching for a solution for this:
Start at a specific time
Have an interval
Exit at a specific time
import schedule
import time
from datetime import datetime as dt
def job():
now = dt.now()
dt_string = now.strftime('%Y-%m-%d %H:%M:%S')
print ("I am working " ,dt_string )#your job function
def schedule_every_four_hours():
job() #for the first job to run
schedule.every(2).minutes.until("09:46").do(job)
print(' 2 Minuten')
return schedule.CancelJob
schedule.every().day.at("09:29").do(schedule_every_four_hours)
while True:
schedule.run_pending()
time.sleep(1)

Categories

Resources