Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - crontab to run a script

Tags:

python

crontab

I'm fairly new to python and I'm trying to create a cronjob through a python script but I keep getting an error. Any help would be greatly appreciated it to show me what I'm doing wrong?

thanks

python script

from crontab import CronTab

cron = CronTab(user=True)

job = cron.new(command='python /Users/<useraccount>/Desktop/my_script.py')
job.minute.on(2)
job.hour.on(12)

cron.write()

Errors:

Traceback (most recent call last):
  File "/Users/<useraccount>/Desktop/01-python-crontab.py", line 3, in <module>
    cron = CronTab(user=True)
TypeError: __init__() got an unexpected keyword argument 'user'
like image 701
Lacer Avatar asked Jul 16 '15 06:07

Lacer


People also ask

How do I run a Python script on a schedule?

Double-click on the Task Scheduler, and then choose the option to 'Create Basic Task…' Type a name for your task (you can also type a description if needed), and then press Next. For instance, let's name the task as: Run Hello World. Choose to start the task 'Daily' since we wish to run the Python script daily at 6am.

Can cron jobs run Python?

Python can be used to schedule the automated execution of preprogrammed tasks using cron.


2 Answers

Here was the issues:

Error showed up: TypeError: init() takes exactly 2 argument

documentaton: https://pypi.python.org/pypi/python-crontab helped to resolve the issue.

Reason: 1 - crontab was installed not python-crontab

Here's the completed code:

def main(): 
    from crontab import CronTab

    cron = CronTab(user=True)

    job = cron.new(command='python /opt/my_script.py')
    job.minute.on(2)
    job.hour.on(12)

    cron.write()

if __name__ == "__main__":
  main()
like image 68
Lacer Avatar answered Oct 20 '22 03:10

Lacer


You may be using an old version of crontab (See - Documentation for 1.4.1 here) . You can either upgrade to latest version of python-crontab using -

pip install python-crontab --upgrade

Or download the 1.9.3 version from here and install it.

If you want to use the old version, you can pass in the username as the argument, Example -

cron = CronTab('<username>')
like image 26
Anand S Kumar Avatar answered Oct 20 '22 03:10

Anand S Kumar