Writing a Python script that runs everyday till a specified date - python

I want to schedule a job (run a python script) everyday at a specific time till a specific date has been reached.
Researching on a lot of Pythonic schedulers, I thought that APScheduler was a good candidate to get around this.
This is an example snippet using APScheduler that starts a job and executes it every two hours after a specified date.
from datetime import datetime
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.start()
def job_function():
print "Hello World"
# Schedule job_function to be called every two hours
sched.add_interval_job(job_function, hours=2)
# The same as before, but start after a certain time point
sched.add_interval_job(job_function, hours=2, start_date='2010-10-10 09:30')
How to achieve the same and have a upper limit date after which the job should not be executed?
Any suggestions that revolve within and outside the APScheduler are most welcome.
Thanks in advance.

Use a cron job that executes your script every two hours (cron is made specifically for things like this). In your script, you just look up the system date and check, if it's smaller than your given date. If it's smaller, you execute the rest of your script, otherwise you quit.
You may also write additional code, so you get notified when the script is not actually executed anymore.

I eventually found the interval trigger can take an end_date.
You can pass arguments for the trigger to add_job with trigger='interval':
sched.add_job(job_function, trigger='interval', hours=2, end_date='2016-10-10 09:30')
I think you may be using an older version of the software.

Related

How to call a function periodically in a script scheduled with crontab?

I wrote a python script which makes calculation at every hour. I run this script with crontab scheduled for every hour. But there is one more thing to do;
Additionally, I should make calculation once a day by using the results evaluated at every hour. In this context, I defined a thread function which checks the current time is equal to the specified time (15:00 PM, once a day ). If it is, thread function is called and calculation made.
What I wanna ask here is; is this approach applicable ? I mean, running the first script at every hour using crontab, and calling the second function using thread function once a day.
Is there any other way of doing this ?
You may use python library sched.
It efficient way to schelude your operations.
You could do a script which runs all the time and just sleeps for one hour.
import time
hours_ran = 0
while True:
# your stuff here
time.sleep(3600)
hours_ran += 1
if hours_ran == 24:
# calculate stuff
hours_ran = 0
This is not necessarily better tho...
You can setup systemd to manage this process.

Detecting change in website Python3

I am taking data from a webpage that updates every morning that updates at different times and I would like to know how to get a script to run every 10 minutes or so to check if the website has been updated. I was thinking of somehow using cron but I don't understand it very well. Thanks for your help.
Have you tried using the package APScheduler? It makes it fairly simple to schedule tasks. Here's the documentation.
To do a scheduled task, this is all that needs to be done (for something basic):
from apscheduler.schedulers.background import BackgroundScheduler
from pytz import utc
scheduler = BackgroundScheduler()
scheduler.configure(timezone=utc)
def print_hello():
print("Hello, this is a scheduled event!")
job = scheduler.add_job(print_hello, 'interval', minutes=1, max_instances=10)
scheduler.start()
Note, however, that I had a small bug when I first tried to use the library, but an explanation of how to fix that is here.

Need pythonic way to schedule one time jobs with arguments

The premise is that I have a script which checks a resource every morning, and retrieves times and URI of events, which will vary from day to day. I want to pass the time and URI location to a scheduler, so that a script designed to capture the event gets called at the event time, passing the location as a variable to the capture script.
At first glance crontab seems like the easiest way to do it, but every job is unique and will only run once, so it creates a lot of maintenance.
I don't have a suggestion for Python specifically, but given that you mentioned crontab as something you were considering, the "one-off" version of a crontab would be at.
'at' tutorial
'at' man page

Is there any Python module available which can alarm after certain time

There is a significant difference between my question and the given one. If I implement sleep as given on the link (which some people think my question is a duplicate of another one) then my whole app will hang for certain time. On the other hand I am looking for a scheduler so that my app will not hang but just after a certain period of time a .wav file will run. Meanwhile I would be able to do anything using my app. Hope that makes sense.
I am going to build an alarm clock. I think I can do this according to this Algorithm...
take current time using time.clock()
compare current time with the given time.
if current time is not given time then continue taking current time and compare whether current time is the given time or not.
if current time is the given time then play the .wav file.
The problem with this program is it will continuously run until the given time. So I am looking for better idea. Let's say if there is any Python module/class/function which can play a sound file on a given time. Is there any Python module/class/function which can wake up on a given time? Or my algorithm is used usually for all alarm clocks?
As far as I know there is not a good Python module to do this. What you are looking for though is a cron job. It allows you to schedule specific scripts to run at certain times. So your Python script would end up just being the code to play the .wav, and then you would need to create a cron job to tell your computer to execute that script at a certain time each day.
Have a look at the sched module.
Here's an example on how to use it:
import sched, time, datetime
def print_time():
print("The time is now: {}".format(datetime.datetime.now()))
# Run 10 seconds from now
when = time.time() + 10
# Create the scheduler
s = sched.scheduler(time.time)
s.enterabs(when, 1, print_time)
# Run the scheduler
print_time()
print("Executing s.run()")
s.run()
print("s.run() exited")
The time is now: 2015-06-04 11:52:11.510234
Executing s.run()
The time is now: 2015-06-04 11:52:21.512534
s.run() exited

Schedule Python Script - Windows 7

I have a python script which I would like to run at regular intervals. I am running windows 7. What is the best way to accomplish this? Easiest way?
You can do it in the command line as follows:
schtasks /Create /SC HOURLY /TN PythonTask /TR "PATH_TO_PYTHON_EXE PATH_TO_PYTHON_SCRIPT"
That will create an hourly task called 'PythonTask'. You can replace HOURLY with DAILY, WEEKLY etc.
PATH_TO_PYTHON_EXE will be something like: C:\python25\python.exe. Check out more examples by writing this in the command line:
schtasks /?
Otherwise you can open the Task Scheduler and do it through the GUI.
Hope this helps.
You can use the GUI from the control panel (called "scheduled tasks") to add a task, most of it should be self-explanatory, but there are two things to watch out for:
Make sure you fill in C:\python27\python.exe as the program path, and the path to your script as the argument.
If you choose Run whether user is logged on or not I get an error: The directory name is invalid (0x87010B). Choosing Run only when user is logged on "solves" this issue.
This took me quite a bit to figure out ...
A simple way to do this is to have a continuously running script with a delay loop. For example:
def doit():
print "doing useful things here"
if __name__ == "__main__":
while True:
doit()
time.sleep(3600) # 3600 seconds = 1 hour
Then leave this script running, and it will do its job once per hour.
Note that this is just one approach to the problem; using an OS-provided service like the Task Scheduler is another way that avoids having to leave your script running all the time.

Categories