Previously, crontab often encountered some problems, such as non-execution of scripts and Error Reporting. Here we record the process and introduce a python tool to automatically change and generate the crontab running script, very friendly to use: plan
I. Installation
$ Pip install plan
II. Create a task script
From plan import Plan
Cron = Plan ()
# Register one command, script or module
# Cron. command ('command', every = '1. Day ')
# Cron. script ('script. Py', path = '/web/yourproject/scripts', every = '1. Month ')
# Cron. module ('Calendar ', every = 'feburary', at = 'Day. 3 ')
If _ name _ = "_ main __":
Cron. run ()
You can also use the following command to automatically create a schedule. py file in the schedule directory.
$ Mkdir schedule
$ Cd schedule
$ Plan-quickstart
III. Use
There are a lot of pitfalls in executing python scripts directly in the crontab configuration file. Finally, we still run it using the sh script. We create a folder bash under the schedule directory and add a new sh script file OneMinitesTask. py
#! /Bin/sh
# The current path is schedule/bash.
Cd ..;
# Activating a virtual environment
Source env/bin/activate;
# Execute the python script
Python OneMinitesTask. py
# Exit the virtual environment
Deactivate
The following is schedule. py
From plan import Plan
# Obtain the bash path (because it depends on the getcwd method, make sure that the running directory is the current directory)
Bash_path = OS. path. abspath (OS. path. join (OS. getcwd (), "bash "))
Cron = Plan ()
# Add a task and execute the TenMinutesTask. sh script once every minute.
# Here the every parameter details see the official website: http://plan.readthedocs.io/job_definition.html#every
Job = Job ('./OneMinutesTask. sh> hello.txt', path = bash_path, every = '1. minute ')
# Add multiple jobs to the plan
Cron. job (job)
If _ name _ = "_ main __":
# Output to the file, overwrite the original task, here there are other parameters, see the official website for details: http://plan.readthedocs.io/run_types.html
Cron. run ('white ')
Run scripts
$ Cd schedule
$ Python schedule. py
[Write] crontab file written
View crontab tasks
$ Crontab-l
# Begin Plan generated jobs for: main
* *** Cd/home/ubuntu/schedule/bash &./OneMinutesTask. sh
# End Plan generated jobs for: main
OK. The test runs successfully. Use the python script to configure crontab to run the script more readable and better maintained.
IV. FAQs
1. You are not sure whether the task is running. You can go to/var/log/cron. log to view the running log of crontab.
$ Vim/var/log/cron. log
Use Shift + G to jump to the last line
If there is no log, it may be that the log service is not enabled, to/etc/rsyslog. d/50-default.conf to view cron. */var/log/cron. whether a log line is commented out. If commented out, the comment is closed.
Sudo vim/etc/rsyslog. d/50-default.conf
# Restart rsyslog after modification
$ Sudo service rsyslog restart