Perl execute a command at a specified time -
i need write perl script executes command @ specified time.
- use net::ssh::expect login router
- read time router's clock ("show clock" command displays time.)
- at 17:30:00 execute command.
i tried writing script doesn't work. suggestions please ?
use strict; use warnings; use autodie; use feature qw/say/; use net::ssh::expect; $time; $ssh = net::ssh::expect->new( host => "ip", password => 'pwd', user => 'user name', raw_pty => 1, ); $login_output = $ssh->login(); while(1) { $time = localtime(); if( $time == 17:30:00 ) { $cmd = $ssh->exec("cmd"); print($cmd); } else { print" failed execute cmd \n"; } }
several things here:
first, use time::piece
. it's included in perl.
use time::piece; (;;) { # prefer using "for" infinite loops $time = localtime; # localtime creates time::piece object # @ $time if ( $time->hms eq "17:30:00" ) { $cmd $ssh->exec("cmd"); print "$cmd\n"; } else { print "didn't execute command\n"; } }
second, shouldn't use loop because you're going tying process looping on , on again. can try sleeping until correct time:
use strict; use warnings; use feature qw(say); use time::piece; $time_zone = "-0500"; # or whatever offset gmt $current_time = local time; $run_time = time::piece( $current_time->mdy . " 17:30:00 $time_zone", # time want run including m/d/y "%m-%d-%y %h:%m:%s %z"); # format of timestamp sleep $run_time - $current_time; $ssh->("cmd"); ...
what did here calculate difference between time want run command , time want execute command. issue if run script after 5:30pm local time. in case, may have check next day.
or, better, if you're on unix, crontab , use that. crontab allow specify when particular command should executed, , don't have worry calculating in program. create entry in crontab table:
30 17 * * * my_script.pl
the 30
, 17
want run script everyday @ 5:30pm. other asterisks day of month, month, , day of week. example, want run program on weekdays:
30 17 * * 1-5 my_script.pl # sunday 0, mon 1...
windows has similar method called schedule control panel can setup jobs run @ particular times. might have use perl my_scipt.pl
, windows knows use perl interpreter executing program.
i highly recommend using crontab route. it's efficient, guaranteed work, allows concentrate on program not finagling when execute program. plus, it's flexible, knows it, , no 1 kill task while sits there , waits 5:30pm.
Comments
Post a Comment