Ubuntu – How to create a cron command that will execute a command inside a detached screen

crongnu-screen

I have created a screen, but can I now somehow execute a command that will run commands in the detached screen?

I do not even know if this is possible, but if it is, it will probably be something simple and easy for you.

Thank you for your effort.

Best Answer

Note: The original poster asked 'how can i do this in cron'. I've updated the response to address that.

  • Get the 'inscreen' script and put it in ~/bin/:

    # download 'inscreen' script from https://gist.github.com/1019125
    wget -O ~/bin/inscreen https://gist.github.com/gists/1019125/download
    chmod 755 ~/bin/inscreen
    
  • create a screen session named 'cronjobs':

    screen -d -m -S cronjobs

    You'll have to arrange for that to happen on each boot, or add '--new-if-needed' to each crontab entry below.

  • Add entries in cron using inscreen, crontab looks like:

    PATH = /home/YOURNAME/bin:/usr/sbin:/usr/bin:/sbin:/bin
    
    * * * * * inscreen cronjobs -- sh -c 'echo $(date): start; sleep 30; echo $(date): end; sleep 4'
    0 0 * * 0 inscreen cronjobs --keep-open --title reminder echo ==== CALL YOUR MOM ====
    0 0 * * 1 inscreen cronjobs --window 0 ls /tmp
    

The above will:

  • every minute open a new window in the 'cronjobs' screen session that writes the date, sleeps for 30 seconds and then exits. The window will close on exit.
  • every sunday at midnight open a new window with title 'reminder' that says "==== CALL YOUR MOM ====" and requires you to hit enter to close the window.
  • every monday at midnight run 'ls /tmp' in the first window of the 'cronjobs' session. Note, though, that no other '--window 0' jobs can be running at the same time.
Related Question