Starting A Process In A "tmux" Session Using Cron


Some processes can be happily run on a regular basis using cron. If you want to start a process every time the system is rebooted, however, it's possible that you want to be able to interact with the process (rather than just letting it run completely in the background).

Fortunately, processes can be started within a tmux session - meaning that you can reconnect to the session whenever you want!

Doing so is pretty simple... create a script, e.g. hello_world.cron, and make it executable (chmod +x hello_world.cron).

A simple example of the script's contents is:

# Sleep for 5 seconds. If you are starting more than one tmux session
#   "at the same time", then make sure they all sleep for different periods
#   or you can experience problems
/bin/sleep 5
# Ensure the environment is available
source /home/USERNAME/.bashrc
# Create a new tmux session named helloworld...
/usr/bin/tmux new-session -d -s helloworld
# ...and control the tmux session (initially ensure the environment
#   is available, then run commands)
/usr/bin/tmux send-keys -t helloworld "source /home/USERNAME/.bashrc" C-m
/usr/bin/tmux send-keys -t helloworld "echo \"hello world!\"" C-m

In order to connect to the session later, use:

tmux attach-session -t helloworld

​And to make the script start every time you reboot, simple edit your crontab:

crontab -e

and add the following line:

@reboot /home/USERNAME/hello_world.cron