简体   繁体   中英

How to run a python script at a certain time in a tmux terminal?

I have a python script, or should I say a python service which needs to run every day at 3pm. Basically, there is a while True : time.sleep(1) at the end of the file.

I absolutely need this script to execute in a terminal window (because I need the logs). Bonus if the solution makes it possible to run in a tmux window.

I tried cron jobs but can't figure out how to put this in a terminal.

I'd suggest sticking with cron and using the tee command to log the results. Your crontab would look something like this:

0 15 * * *     python yourScript.py | tee –a logFile.txt

Okay, I see what you're saying. I've done some similar stuff in the past.

For the cron to run your script at 3pm and append to a log file you can do that simply like this:

0 15 * * * command >> log # just logs stdout

or

0 15 * * * command &>> log # logs both stdout and stderr

If you want it in the terminal I can think of two possibilities:

  • Like you said, you could do a while true loop that checks the time every n seconds and when it's 3pm do something.

  • Alternately you could set up an API endpoint that's always on and trigger it by some other program at 3pm. This could be triggered by the cron for example.

Personally I also like the convenience of having a tmux or screen to login to to see what's been happening rather than just checking a log file. So I hope you figure out a workable solution for your use case!

As mentioned above cronjob that redirects output to a file might be the simplest but if that is not possible an you want to keep process running you can set timeout till next day 3pm.

h_exec = 15
t_hour = 60 * 60
t_day = 24 * t_hour
t_now = time.time()
t_timeout = math.floor((t_now + ((24 - h_exec) * t_hour)) / t_day) * t_day + (h_exec * t_hour) - t_now

thanks all for the answers. I used a cron job with a bash script for TMUX Scripting.

Something like that :

#!/bin/bash
tmux new-session -d -s example
tmux split-window -h
tmux select-pane -t 0
tmux send-keys './ex.sh' 'C-m'
tmux select-pane -t 1
tmux send-keys './ex1.sh'
tmux new-window -n 'a'
tmux send-keys 'cd a' 'C-m'
tmux select-window -t "example:0"
tmux select-pane -t 0
tmux -2 attach-session -t example

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