Search code examples
ubuntucronrestart

How to restart a process every 4 hours using crontab?


Could someone tell me how to restart a process every 4 hours using crontab? I have a Starbound server running (which is a game like Terarria which recently came out) and it's taking a lot of resources, so I'd like to kill the process then start it back up every 6 hours.

What I think I would need to do in crontab is:

kill -9 | grep starbound_server cd /home/steam/starbound/linux64 && screen -S starbound -d -m ./launch_starbound_server.sh

But I am not sure about this and don't understand the time thingy either.

I hope someone can help me :)


Solution

  • crontab works like this.

    # .---------------- minute (0 - 59)
    # |  .------------- hour (0 - 23)
    # |  |  .---------- day of month (1 - 31)
    # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
    # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
    # |  |  |  |  |
    # *  *  *  *  * user-name  command to be executed
    

    So if you want to run your script every minute on 4 hour intervals, you'd have to add this line to crontab file.

    * */4 * * * user-name command to be executed
    

    To run your script once every 4 hours (on the zero minute), you'd have to add this line to crontab file.

    0 */4 * * * user-name command to be executed
    

    Edit ( Answer to comment ):

    Yes, I believe this is correct, but as myself I usually do separate file for this, for example, script.sh to keep things clean.

    For example with contents:

    #!/bin/sh
    
    # Kill 1
    screen -X -S | grep starbound kill 
    
    # Kill 2
    kill -9 | grep starbound_server
    
    # Change directory  
    cd /home/steam/starbound/linux64
    
    # Start the server again 
    screen -S starbound -d -m ./launch_starbound_server.sh
    

    You can save it to the location you like and use:

    chmod +x yourcript.sh
    

    to make it executable, and then add it to crontab.