简体   繁体   中英

Why is Python not setting up my cron job's time properly?

I created a python script which adds a data entry in a mysql database every 1 minute. For that, I used cron inside python.Here's the code of script1.py:

import MySQLdb as mdb
from crontab import CronTab

con=mdb.connect('localhost','prabakar','****','timedb');
with con:
    cur=con.cursor()
    cur.execute("DROP TABLE IF EXISTS timer")
    cur.execute("CREATE TABLE timer(Time TIME)")
    cur.execute("INSERT INTO timer(Time) VALUES(CURRENT_TIMESTAMP)")
cron= CronTab(user=True)
job=cron.new(command='/home/praba1110/Delta_sysad_tasks/Task  2/script2.py')
job.minute.every(1)
cron.write()

Where script2.py is,

    import MySQLdb as mdb
    con=mdb.connect('localhost','prabakar','****','timedb');
    with con:
          cur=con.cursor()
          cur.execute("INSERT INTO timer(Time) VALUES(CURRENT_TIMESTAMP)")

When I executed the command 'crontab -e' command in my terminal, it showed an entry of

    * * * * * /home/praba1110/Delta_sysad_tasks/Task  2/script2.py

instead of,

    */1 * * * * /home/praba1110/Delta_sysad_tasks/Task  2/script2.py

When I made the 2nd script run seperately, it did run and appended the current time in the table.But when trying to execute from script1, it isn't working.The script 2 is not getting executed from script 1. PS: I did give rwx permissions to script2.py

Can anyone tell why script1.py isn't working or what the problem is?


Solved

It works if we give
job=cron.new(command='/user/bin/python2 "/home/praba1110/Delta_sy sad_tasks/Task 2/script2.py" ')

* * * * * /home/praba1110/Delta_sysad_tasks/Task  2/script2.py

is equivalent to

*/1 * * * * /home/praba1110/Delta_sysad_tasks/Task  2/script2.py

Neither of these crontab entries will work however, since the shell will try to execute

/home/praba1110/Delta_sysad_tasks/Task

and pass to it the argument 2/script2.py . Instead, you'll need to protect the spaces in the directory path by enclosing the command in quotes:

job=cron.new(command='/path/to/python "/home/praba1110/Delta_sysad_tasks/Task  2/script2.py"')

so that the crontab entry becomes

* * * * * /path/to/python "/home/praba1110/Delta_sysad_tasks/Task  2/script2.py"

Note that handling spaces correctly is possible by often an annoyance. You might want to avoid spaces in paths to make your life easier.

Per Moo's suggestion, I've also added an explicit absolute path to the python executable since by default cron jobs do not see the same environment variables (such as PATH) as you would see when logged on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM