53

Hi I have created a python file for example as file_example.py

The file will output the sensex value

Suppose the path of the file on linux system is /Desktop/downloads/file_example.py

and I normally will run the file like python file_example.py

But I want to set a cron job to run the python file every 2 min which is located at the above path

Can anyone please let me know how to do this

Edited Code:

I had edited the code and created a bash script with the name test.sh as indicated below

#!/bin/bash 
cd /Desktop/downloads/file_example.py
python file_example.py 2>log.txt 

When I run the above file, the following error is displayed:

sh-4.2$ python test.sh
  File "test.sh", line 3
    python test.py 2>log.txt 
              ^
SyntaxError: invalid syntax
Ryan
  • 2,167
  • 2
  • 28
  • 33
Shiva Krishna Bavandla
  • 25,548
  • 75
  • 193
  • 313

2 Answers2

60

Assuming you are using a unix OS, you would do the following.

edit the crontab file using the command

crontab -e

add a line that resembles the one below

*/2 * * * * /Desktop/downloads/file_example.py

this can be used to run other scripts simply use the path to the script needed i.e.

*/2 * * * * /path/to/script/to/run.sh

An explanation of the timing is below (add a star and slash before number to run every n timesteps, in this case every 2 minutes)

* * * * * command to be executed
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)
Community
  • 1
  • 1
olly_uk
  • 11,559
  • 3
  • 39
  • 45
39

You can use python-crontab module.

https://pypi.python.org/pypi/python-crontab

To create a new cron job is as simple as follows:

from crontab import CronTab
#init cron
cron   = CronTab()

#add new cron job
job  = cron.new(command='/usr/bin/echo')

#job settings
job.hour.every(4)
Guray Celik
  • 1,281
  • 1
  • 14
  • 13
  • 12
    I don't know how come nobody happened to mention this till now. But one needs to add `cron.write()` to this code to actually make it work. I found this from here - http://stackabuse.com/scheduling-jobs-with-python-crontab/ – akki Jun 21 '18 at 06:11
  • @Guray Celik I am also using same module my cronjobs process are running but it doesnot executing code.I tried with somany script even like printing – Narender Reddy Feb 28 '19 at 05:38