我正在Perl中编写一个需要每晚同时运行的脚本,除非有时需要更改.我在CPAN上找到了
Schedule::Cron,它完成了我想要它做的事情.根据run方法的文档,
nofork => 1
Don’t fork when starting the scheduler. Instead,the jobs are executed within current process. In your executed jobs,you have full access to the global variables of your script and hence might influence other jobs running at a different time.
这是我想做的,但它没有做.每当我检查全局变量的内存位置时,它们都是相同的,但是当任务开始时,该值不会更改.
我在Windows和Linux上都运行了这个,我让其他人查看代码,看看我的逻辑是否正确.我需要做些什么来保持对全局变量的更改.
use warnings; use strict; use Schedule::Cron; use Time::localtime; use constant { EVERY_DAY_10PM => '* * * * * 4,16,28,40,52',EVERY_DAY_NOON => '* * * * * 0,12,24,36,48',EVERY_DAY_2AM => '* * * * * 7,19,31,43,55' }; ############GLOBAL VARIABLES############ our $cron = new Schedule::Cron(\&runUpdate); our $cronId; our $updateTimeDirty = 0; ############END GLOBAL VARIABLES############ ############MAIN PROGRAM BODY############ $cronId = $cron->add_entry(EVERY_DAY_10PM);#defaults to \&runUpdate $cron->add_entry(EVERY_DAY_NOON,\&changeTime); $cron->run(no_fork => 1); ############END MAIN PROGRAM BODY############ sub changeTime { our $cron; our $cronId; our $updateTimeDirty; print "updateTimeDirty is $updateTimeDirty\n"; print "udpateTimeDirty location: " . \$updateTimeDirty . "\n"; print "cron object: " . \$cron . "\n"; if ($updateTimeDirty) { my $cronEntry = $cron->get_entry($cronId); $cronEntry->{time} = EVERY_DAY_2AM; $cron->update_entry($cronId,$cronEntry); } print "\n"; } sub runUpdate { our $updateTimeDirty; $updateTimeDirty = 1; print "Updating at " . localtime()->sec . " ($updateTimeDirty)\n\n"; }
解决方法
no_fork和nofork之间存在显着差异.尝试:
$cron->run(nofork => 1);