Schedule Python Script - Windows 7 - python

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.

Related

My Python Script does not run from Task Scheduler

I have a script which I want to run on a daily basis at the same time, automatically. I tried to use Windows Task Scheduler. but no luck so far. FYI I can run the same script from the console without any issue.
I tried
where python
C:\Users\name\Anaconda3\python.exe
C:\Users\name\AppData\Local\Programs\Python\Python38\python.exe
C:\Users\name\AppData\Local\Microsoft\WindowsApps\python.exe
on TaskScheduler
Program/script: "C:\Users\name\AppData\Local\Programs\Python\Python38\python.exe"
Add arguments: Nomura_Daily_PnL_Check.py
Start in: "C:\Users\name\Jobs\scripts_need_to_run_daily"
when the scheduled time come, literally nothing happens. No error, No output, nothing!
what is wrong in this process?
try mentioning values without double inverted commas, like:
Program/script: C:\Users\name\AppData\Local\Programs\Python\Python38\python.exe
Add arguments: Nomura_Daily_PnL_Check.py
Start in: C:\Users\name\Jobs\scripts_need_to_run_daily
Also first try to run a simple program, lets say a python program which will write to a file so that you will know whether task is failing or there is some issue with your program.

How can I have my script run certain days / months

I have just created a python script that automatically renews my pass. Is it possible to make the script run like a app or a background program to check if it is a certain day of a month and to run it?
That's just scheduled task.
In your task call python.exe, pass your script as an argument and that's it.

Writing a Python script that runs everyday till a specified date

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.

Automate Python Script

I'm running a python script manually that fetches data in JSON format.How do I automate this script to run automatically on an hourly basis?
I'm working on Windows7.Can I use tools like Task scheduler?If I can use it,what do I need to put in the batch file?
Can I use tools like Task scheduler?
Yes. Any tool that can run arbitrary programs can run your Python script. Pick the one you like best.
If I can use it,what do I need to put in the batch file?
What batch file? Task Scheduler takes anything that can be run, with arguments—a C program, a .NET program, even a document with a default app associated with it. So, there's no reason you need a batch file. Use C:\Python33\python.exe (or whatever the appropriate path is) as your executable, and your script's path (and its arguments, if any) as the arguments. Just as you do when running the script from the command line.
See Using the Task Scheduler in MSDN for some simple examples, and Task Scheduler Schema Elements or Task Scheduler Scripting Objects for reference (depending on whether you want to create the schedule in XML, or via the scripting interface).
You want to create an ExecAction with Path set to "C:\Python33\python.exe" and Arguments set to "C:\MyStuff\myscript.py", and a RepetitionPattern with Interval set to "PT1H". You should be able to figure out the rest from there.
As sr2222 points out in the comments, often you end up scheduling tasks frequently, and needing to programmatically control their scheduling. If you need this, you can control Task Scheduler's scripting interface from Python, or build something on top of Task Scheduler, or use a different tool that's a bit easier to get at from Python and has more helpful examples online, etc.—but when you get to that point, take a step back and look at whether you're over-using OS task scheduling. (If you start adding delays or tweaking times to make sure the daily foo1.py job never runs until 5 minutes after the most recent hourly foo0.py has finished its job, you're over-using OS task scheduling—but it's not always that obvious.)
May I suggest WinAutomation or AutoMate. These two do the exact same thing, except the UI is a little different. I prefer WinAutomation, because the scripts are a little easier to build.
Yes, you can use the Task Scheduler to run the script on an hourly bases.
To execute a python script via a Batch File, use the following code:
start path_to_python_exe path_to_python_file
Example:
start C:\Users\harshgoyal\AppData\Local\Continuum\Anaconda3\python.exe %UserProfile%\Documents\test_script.py
If python is set as Window’s Environment Window then you can reduce the syntax to:
start python %UserProfile%\Documents\test_script.py
What I generally do is run the batch file once via Task Scheduler and within the python script I call a thread/timer every hour.
class threading.Timer(interval, function, args=None, kwargs=None)

How can I run my python script in the background on a schedule?

I have a small python script that creates a graph of data pulled from MySQL. I'm trying to figure out a way to run the script in the background all time on a regular basis. I've tried a number of things:
A Cron Job that runs the script
A loop timer
Using the & command to run the script in the background
These all have there pluses and minuses:
The Cron Job running more then every half hour seems to eat up more resources then it's worth.
The Loop timer put into the script doesn't actually put the script in the background it just keeps it running.
The Linux & command backgrounds the process but unlike a real Linux service I can't restart/stop it without killing it.
Can someone point me to a way to get the best out of all of these methods?
Why don't you try to make your script into a proper daemon. This link is a good place to start.
import os
import subprocess
import time
from daemon import runner
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/your-pid-name.pid'
self.pidfile_timeout = 5
def run(self):
try:
while True:
### PUT YOUR SCRIPT HERE ###
time.sleep(300)
except Exception, e:
raise
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
You can start/stop/restart this script just like any other linux service.
The cron job is probably a good approach in general, as the shell approach requires manual intervention to start it.
A couple of suggestions:
You could use a lock file to ensure that the cron job only ever starts one instance of the python script - often problems occur when using cron for larger jobs because it starts a second instance before the first instance has actually finished. You can do this simply by checking whether the lock file exists, then, if it does not, 'touch'ing the file at the beginning of the script and 'rm'ing it as your last action at the end of the script. If the lock file exists -- simply exit the script, as there is already one instance running. (Of course, if the script dies you will have to delete the lock file before running the script again).
Also, if excessive resource use is a problem, you can ensure that the script does not eat too many resources by giving it a low priority (prefix with, for example, nice -n 19).

Categories