Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate a cron job

I want to run a script once day (and only on weekends), however, I cannot use cron job for that.

I was thinking about having an infinite while loop, sleep for 24 hours, check if it is a weekend, and if so execute the script.

What it's a good solution under bash on linux?

my current implementation:

#! /bin/bash

 while [ true ]; do
    if [[ $(date +%u) -lt 6 ]]; then
               ./program
        else
             echo Today is a weekend, processing is skipped. Back to sleep.
    fi
    sleep  86400
done

And I will launch this script at 5 pm.

like image 439
vehomzzz Avatar asked Aug 20 '10 17:08

vehomzzz


2 Answers

Back in the day when there were no per-user crontabs, I often accomplished this using at(1).

#!/bin/sh
... do stuff...
at -f /path/to/me 5pm tomorrow

This way your script runs and schedules itself for the next invocation.

I don't think you can specify a timespec of "next weekend", so you'll just have to reschedule every day and have your script exit (after scheduling the next at job) if it is not a weekend.

Edit: Or instead of scheduling every day, find out what today is and schedule appropriately. e.g.

day=Saturday
if [ $(date +%u) -eq 6 ] ; then day=Sunday ; fi
at -f /path/to/me 5pm next $day

If this script is run on a Saturday, it schedules the next run for next Sunday, otherwise it runs next Saturday. [ $(date +%A) = Saturday ] may be more readable, buts %A will give a locale-specific string so may not work if you change locale.

like image 108
camh Avatar answered Oct 08 '22 03:10

camh


For a Perl solution then take a look at Schedule::Cron CPAN module:

use 5.012;
use warnings;
use Schedule::Cron;

my $cron = Schedule::Cron->new( sub {} );

# add weekend run @ 05:00 
$cron->add_entry('0 5 * * Sat,Sun', sub {
    system './program';
});

$cron->run();
like image 20
draegtun Avatar answered Oct 08 '22 03:10

draegtun