Rabb-bit
Rabb-bit

Reputation: 835

how to run sh script every hour without using cron and only using infinite loop?

We do not have permission to use cron and at command in our environment. I would like to run an sh file every hour.

I'm thinking of this code but I am not sure if this is the most elegant approach. Please advise. Below there is the pseudo code.

I'm just doing an infinite loop and then looping through array of 24 value to represent hours:

array24 = 1:00,2:00,3:00 to 00:00
while [[ ! -f /home/22/job_stop.txt ]]
do
  #TIME=`date +%H%M|bc`
  currentHour=date '+%H:00'
    for loop array24 
    if  [$currentHour -eq $array24 ] || 

    then
            /folder/1/script.sh
    fi
    end for
  sleep 900
done
exit

Upvotes: 0

Views: 5751

Answers (2)

Indent
Indent

Reputation: 4967

Python is your friend !

With a shebang line you can easly call a python program from shell :

#!/usr/bin/env python
import schedule
import time
import subprocess
import os    

def cmd() :
    # Call your command here
    subprocess.call(["/folder/1/script.sh"])

schedule.every(1).hour.do(cmd)

while not os.path.exists("/home/22/job_stop.txt")
    schedule.run_pending()
    time.sleep(1)

Upvotes: 0

Keith Thompson
Keith Thompson

Reputation: 263547

Here's an example:

#!/bin/bash

interval=3600
while [[ ! -f /home/22/job_stop.txt ]] ; do
    now=$(date +%s) # timestamp in seconds
    sleep $((interval - now % interval))
    # do something            
done

A simple sleep 3600 would cause the timing to drift, as the command you execute takes time. This computes the number of seconds until the top of the next hour, and sleeps for that long. (If the command takes more than an hour, it will skip one or more iterations, but the next iteration will occur at the top of the hour.)

Note that this checks for a whole number of hours since the Unix epoch. If you change the interval to 86400 (one day), it will execute at midnight UTC.

Upvotes: 3

Related Questions