How to perform a command at a set time each day / hour/ otherwise.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
SokenDev af17953a01 Update 'README.md' 8 months ago
README.md Update 'README.md' 8 months ago

README.md

LinuxAutoRestart

How to perform a command at a set time each day / hour/ otherwise.

Prerequisites

This tutorial will cover how to perform a single command at a set time on a repeat schedule. If you want to restart something automatically, you need to be able to do so with a single command. This tutorial will not acknowledge the existence of any permission-related issues, they are your own problem to ensure they're correct.
You can either start a process, store it's PID, and kill it, or you can use a service manager such as Systemd.

Commands

  1. Change to home directory: cd ~
  2. Create new folder: mkdir autorestart
  3. Create bash file to run: touch loop.sh
  4. Edit bash file using nano (you can use vim etc): nano loop.sh
  5. Enter the commands you want to be run (this simply restarts a running service called myservice):
#!/bin/bash
systemctl restart myservice
  1. Save the file (Ctrl+X, Y, Enter)

Create Cron Job

Operators

Cronjobs support 4 operators:

  • * : All values, e.g. every minute, every month, etc.
  • , : Separate individual values.
  • - : Range of values.
  • / : Divides a value into multiple steps, e.g. */2 = every second minute/month/etc, */3 = every third minute/month/etc.

Syntax

Cronjobs are a single line each, following this syntax:

minute hour day month dayofweek /path/to/command.sh output
Their possible values are:

  • Minute: 0-59
  • Hour: 0-23
  • Day: 0-31
  • Month: 0 = None, 1-12 = January-December
  • Day of the Week: 0-7 = Sunday-Sunday (1 whole week)
  • Path to Command: Must point to an executable file for the job to run.
  • Output: How the success/failure of the job will be reported. By default, will send you an email. You can disable the output functionality by using >/dev/null 2>&1 here.

Examples

  • Run command.sh every 30 minutes: 30 * * * * /path/to/command.sh
  • Run command.sh at 5am each day: 0 5 * * * /path/to/command.sh
  • Run command.sh at 1st Thursday of each month, at 7:15pm: 15 19 * * 4 /path/to/command.sh

Usage

  1. Open the crontab file: crontab -e
  2. Move your cursor to the bottom and create a newline
  3. Enter your cronjob using the above syntax
  4. Save the file
  5. You're done, nothing needs to be restarted for it to go into effect.