Several things here:
First, use Time::Piece
. It's now included in Perl.
use Time::Piece;
for (;;) { # I prefer using "for" for infinite loops
my $time = localtime; # localtime creates a Time::Piece object
# I could also simply look at $time
if ( $time->hms eq "17:30:00" ) {
my $cmd $ssh->exec("cmd");
print "$cmd\n";
}
else {
print "Didn't execute command\n";
}
}
Second, you shouldn't use a loop like this because you're going to be tying up a process just looping over and over again. You can try sleeping until the correct time:
use strict;
use warnings;
use feature qw(say);
use Time::Piece;
my $time_zone = "-0500"; # Or whatever your offset from GMT
my $current_time = local time;
my $run_time = Time::Piece(
$current_time->mdy . " 17:30:00 $time_zone", # Time you want to run including M/D/Y
"%m-%d-%Y %H:%M:%S %z"); # Format of timestamp
sleep $run_time - $current_time;
$ssh->("cmd");
...
What I did here was calculate the difference between the time you want to run your command and the time you want to execute the command. Only issue if I run this script after 5:30pm local time. In that case, I may have to check for the next day.
Or, even better, if you're on Unix, look up the crontab and use that. The crontab will allow you to specify exactly when a particular command should be executed, and you don't have to worry about calculating it in your program. Simply create an entry in the crontab table:
30 17 * * * my_script.pl
The 30
and 17
say you want to run your script everyday at 5:30pm. The other asterisks are for day of the month, the month, and the day of the week. For example, you only want to run your program on weekdays:
30 17 * * 1-5 my_script.pl # Sunday is 0, Mon is 1...
Windows has a similar method called the Schedule Control Panel where you can setup jobs that run at particular times. You might have to use perl my_scipt.pl
, so Windows knows to use the Perl interpreter for executing your program.
I highly recommend using the crontab route. It's efficient, guaranteed to work, allows you to concentrate on your program an not finagling when to execute your program. Plus, it's flexible, everyone knows about it, and no one will kill your task while it sits there and waits for 5:30pm.