Set cron from 1 on Ubuntu 16.04 (Sakura VPS) and execute python program regularly

Purpose

I want to automatically execute a python program on Ubuntu on a regular basis. I set cron from 1.

environment

OS: Ubuntu16.04 (Sakura VPS) python : Version 3.5

CRON initial settings

Operation 1) CRON operation check </ b>

sudo service cron status

Various CRON statuses are displayed, If it says "Active: active (running)", it should be OK.

If it's not working

service crond start

Start with.

Operation 2) Register the job in the cron configuration file </ b>

You can execute crontab, which is a cron configuration file, with the following command.

crontab -e

However, if you accidentally press r next to e on your keyboard, "crontab -r" will initialize all crontab settings, so it is dangerous to use "crontab -e" frequently.

There are multiple ways to avoid using crontab -e, but I follow the steps below to make a backup and edit it separately.

crontab -l > ~/crontab #backup
vim ~/crontab        #Edit backup
crontab < ~/crontab  #Overwrite the main body

Details on how to write crontab are described on other sites, so it is a good idea to refer to that. For example, here was easy to understand.

When executing a python program, you must write the path where python is stored before the program.

For example, if you want to run test.py every minute,

* * * * * /<path_to_python>/python3 /<path_to_file>/test.py 

It will be.

If you don't know the path to python

which python3

You can find out at.

If you want to output the log,

* * * * * <path_to_python>/python3 /<path_to_file/test.py >> /<path_to_log>/test.log 2>>&1

Will be fine.

Operation 3) Change file permissions </ b>

Basically, the settings up to operation 2 are fine, but in my case I got a Permission Denied error. Since the execution permission of CRON is root and the owner of the file is another user, there is no Permission due to the permission setting.

For the time being, change it to "Owner: root, privilege 700".

chmod 700 test.py
chown root:root test.py

Now test.py is automatically run on a regular basis.

Recommended Posts