In this paper, we mainly introduce two methods of executing Python script in timed cycle in Linux environment.
Method One: Nohup
Vim time.py
1importtime 2 while (True): 3 #time. Sleep (1) 4 Open ('time. Log ', ' A + ') as logfile: 5 logfile. Write(' Hello, world!\n ') 6time . Sleep (1) 7 #break
Run the following command at the terminal
time. PY &
Function: Implements a "Hello, world!" string per second, written to the Time.log file in the current directory.
Principle: Take advantage of Python's infinite Loop while (True), and use the Time.sleep () method to set the corresponding number of seconds to stop, and finally, through the Nohup and & commands to hang the script in the background do not hang up the run.
Nohup command &: commandis run in the background, standard output and errors of the original program are redirected to the Nohup.out file in the current directory. If the nohup.out file for the current directory is not writable, the output is redirected to the $HOME/nohup.out file.
View: Through Tail-f Time.log in the current terminal trace display Time.log file, can use CTRL + C interrupt display.
Interrupts: View tasks running in the current background through the jobs command, then use FG%n to hook the nth item to the foreground, and then use CTRL + C to interrupt the task.
or via PS aux | The grep python command looks at the Python process, finds the PID of the pending script, and then interrupts the pending script using the Kill-9 PID.
Outreach: Nohup and & background operations, process viewing and termination, use of the Linux nohup command
Method Two: Cron
Vim time.py
1open('/home/titanxp/test/time. Log ', ' A + ') as logfile: 2 logfile . Write (' Hello, world!\n ')
Use the CRONTAB-E command in the terminal to set up the following tasks
*/1 * * * */usr/bin/python/home/titanxp/test/time. py
Function: The "Hello, world!" string is implemented every minute, written to the Time.log file in the specified directory.
Principle: establish periodic tasks by CRONTAB-E command. Note that the script and the script path need to write the full path.
Crontab format: Minute hour day-of-month month-of-year day-of-week commands
View: View cron logs with the Tail-f/var/log/cron.log command to see if the task is executing.
Interrupt: Open for task editing via crontab-e, just delete or comment (#) The scheduled task can be interrupted.
Expand: Crontab command, Linux timed execution script
Summarize
Method one uses the Python time library to implement a simple timed loop execution script, which can be applied to the situation where the variables need to be accumulated.
Method two combines the cron command to implement a complex timed loop execution script.
The above statement may not be in place, welcome to exchange discussions.
Linux timed loop executes Python script