1 package Catalyst::Plugin::Scheduler;
5 use base qw/Class::Accessor::Fast Class::Data::Inheritable/;
7 use DateTime::Event::Cron;
8 use DateTime::TimeZone;
12 use Storable qw/lock_store lock_retrieve/;
14 our $VERSION = '0.07';
16 __PACKAGE__->mk_classdata( '_events' => [] );
17 __PACKAGE__->mk_accessors('_event_state');
20 my ( $class, %args ) = @_;
22 unless ( $args{event} ) {
23 Catalyst::Exception->throw(
24 message => 'The schedule method requires an event parameter' );
27 my $conf = $class->config->{scheduler};
30 trigger => $args{trigger},
31 event => $args{event},
32 auto_run => ( defined $args{auto_run} ) ? $args{auto_run} : 1,
37 # replace keywords that Set::Crontab doesn't support
38 $args{at} = _prepare_cron( $args{at} );
40 # parse the cron entry into a DateTime::Set
42 eval { $set = DateTime::Event::Cron->from_cron( $args{at} ) };
44 Catalyst::Exception->throw(
45 "Scheduler: Unable to parse 'at' value "
50 $event->{at} = $args{at};
55 push @{ $class->_events }, $event;
61 $c->NEXT::dispatch(@_);
63 $c->_get_event_state();
67 # check if a minute has passed since our last check
68 # This check is not run if the user is manually triggering an event
69 if ( time - $c->_event_state->{last_check} < 60 ) {
70 return unless $c->req->params->{schedule_trigger};
72 my $last_check = $c->_event_state->{last_check};
73 $c->_event_state->{last_check} = time;
74 $c->_save_event_state();
76 my $conf = $c->config->{scheduler};
77 my $last_check_dt = DateTime->from_epoch(
79 time_zone => $conf->{time_zone}
81 my $now = DateTime->now( time_zone => $conf->{time_zone} );
84 for my $event ( @{ $c->_events } ) {
87 if ( $event->{trigger} && $c->req->params->{schedule_trigger}
88 && $event->{trigger} eq $c->req->params->{schedule_trigger} )
91 # manual trigger, run it now
92 next EVENT unless $c->_event_authorized;
96 next EVENT unless $event->{set};
97 $next_run = $event->{set}->next($last_check_dt);
100 if ( $next_run <= $now ) {
102 # do some security checking for non-auto-run events
103 if ( !$event->{auto_run} ) {
104 next EVENT unless $c->_event_authorized;
107 # make sure we're the only process running this event
108 next EVENT unless $c->_mark_running($event);
110 my $event_name = $event->{trigger} || $event->{event};
111 $c->log->debug("Scheduler: Executing $event_name")
112 if $c->config->{scheduler}->{logging};
115 local $c->{error} = [];
117 # return value/output from the event, if any
123 # do not allow the event to modify the response
124 local $c->res->{body};
125 local $c->res->{cookies};
126 local $c->res->{headers};
127 local $c->res->{location};
128 local $c->res->{status};
130 if ( ref $event->{event} eq 'CODE' ) {
131 $output = $event->{event}->($c);
134 $output = $c->forward( $event->{event} );
137 my @errors = @{ $c->{error} };
138 push @errors, $@ if $@;
141 'Scheduler: Error executing ' . "$event_name: $_" )
143 $output = join '; ', @errors;
146 $c->_mark_finished( $event, $output );
154 # initial configuration
155 $c->config->{scheduler}->{logging} ||= ( $c->debug ) ? 1 : 0;
156 $c->config->{scheduler}->{time_zone} ||= $c->_detect_timezone();
157 $c->config->{scheduler}->{state_file} ||= $c->path_to('scheduler.state');
158 $c->config->{scheduler}->{hosts_allow} ||= '127.0.0.1';
159 $c->config->{scheduler}->{yaml_file} ||= $c->path_to('scheduler.yml');
167 return ( $c->NEXT::dump_these(@_) ) unless @{ $c->_events };
169 # for debugging, we dump out a list of all events with their next
172 $c->NEXT::dump_these(@_),
173 [ 'Scheduled Events', $c->scheduler_state ],
177 sub scheduler_state {
180 $c->_get_event_state();
182 my $conf = $c->config->{scheduler};
183 my $now = DateTime->now( time_zone => $conf->{time_zone} );
185 my $last_check = $c->_event_state->{last_check};
186 my $last_check_dt = DateTime->from_epoch(
187 epoch => $last_check,
188 time_zone => $conf->{time_zone},
192 for my $event ( @{ $c->_events } ) {
194 for my $key ( qw/at trigger event auto_run/ ) {
195 $dump->{$key} = $event->{$key} if $event->{$key};
198 # display the next run time
199 if ( $event->{set} ) {
200 my $next_run = $event->{set}->next($last_check_dt);
203 . q{ } . $next_run->hms
204 . q{ } . $next_run->time_zone_short_name;
207 # display the last run time
209 = $c->_event_state->{events}->{ $event->{event} }->{last_run};
211 $last_run = DateTime->from_epoch(
213 time_zone => $conf->{time_zone},
217 . q{ } . $last_run->hms
218 . q{ } . $last_run->time_zone_short_name;
221 # display the result of the last run
223 = $c->_event_state->{events}->{ $event->{event} }->{last_output};
225 $dump->{last_output} = $output;
228 push @{$event_dump}, $dump;
234 # check and reload the YAML file with schedule data
238 # each process needs to load the YAML file independently
239 if ( $c->_event_state->{yaml_mtime}->{$$} ||= 0 ) {
240 return if ( time - $c->_event_state->{last_check} < 60 );
243 return unless -e $c->config->{scheduler}->{yaml_file};
246 my $mtime = ( stat $c->config->{scheduler}->{yaml_file} )->mtime;
247 if ( $mtime > $c->_event_state->{yaml_mtime}->{$$} ) {
248 $c->_event_state->{yaml_mtime}->{$$} = $mtime;
250 # clean up old PIDs listed in yaml_mtime
251 foreach my $pid ( keys %{ $c->_event_state->{yaml_mtime} } ) {
252 if ( $c->_event_state->{yaml_mtime}->{$pid} < $mtime ) {
253 delete $c->_event_state->{yaml_mtime}->{$pid};
256 $c->_save_event_state();
258 # wipe out all current events and reload from YAML
261 my $file = $c->config->{scheduler}->{yaml_file};
264 eval { require YAML::Syck; };
267 $yaml = YAML::LoadFile( "$file" );
270 open( my $fh, $file ) or die $!;
271 my $content = do { local $/; <$fh> };
273 $yaml = YAML::Syck::Load( $content );
276 foreach my $event ( @{$yaml} ) {
277 $c->schedule( %{$event} );
280 $c->log->info( "Scheduler: PID $$ loaded "
282 . ' events from YAML file' )
283 if $c->config->{scheduler}->{logging};
287 $c->log->error("Scheduler: Error reading YAML file: $@");
291 # Detect the current time zone
292 sub _detect_timezone {
296 eval { $tz = DateTime::TimeZone->new( name => 'local' ) };
299 'Scheduler: Unable to autodetect local time zone, using UTC')
300 if $c->config->{scheduler}->{logging};
305 'Scheduler: Using autodetected time zone: ' . $tz->name )
306 if $c->config->{scheduler}->{logging};
311 # Check for authorized users on non-auto events
312 sub _event_authorized {
315 # this should never happen, but just in case...
316 return unless $c->req->address;
318 my $hosts_allow = $c->config->{scheduler}->{hosts_allow};
319 $hosts_allow = [$hosts_allow] unless ref($hosts_allow) eq 'ARRAY';
320 my $allowed = Set::Scalar->new( @{$hosts_allow} );
321 return $allowed->contains( $c->req->address );
324 # get the state from the state file
325 sub _get_event_state {
328 if ( -e $c->config->{scheduler}->{state_file} ) {
330 lock_retrieve $c->config->{scheduler}->{state_file} );
334 # initialize the state file
336 { last_check => time,
341 $c->_save_event_state();
345 # Check the state file to ensure we are the only process running an event
347 my ( $c, $event ) = @_;
349 $c->_get_event_state();
352 $c->_event_state->{events}->{ $event->{event} }->{running};
354 # this is a 2-step process to prevent race conditions
355 # 1. write the state file with our PID
356 $c->_event_state->{events}->{ $event->{event} }->{running} = $$;
357 $c->_save_event_state();
359 # 2. re-read the state file and make sure it's got the same PID
360 $c->_get_event_state();
361 if ( $c->_event_state->{events}->{ $event->{event} }->{running} == $$ ) {
368 # Mark an event as finished
370 my ( $c, $event, $output ) = @_;
372 $c->_event_state->{events}->{ $event->{event} }->{running} = 0;
373 $c->_event_state->{events}->{ $event->{event} }->{last_run} = time;
374 $c->_event_state->{events}->{ $event->{event} }->{last_output} = $output;
375 $c->_save_event_state();
378 # update the state file on disk
379 sub _save_event_state {
382 lock_store $c->_event_state, $c->config->{scheduler}->{state_file};
385 # Set::Crontab does not support day names, or '@' shortcuts
389 return $cron unless $cron =~ /\w/;
415 'yearly' => '0 0 1 1 *',
416 'annually' => '0 0 1 1 *',
417 'monthly' => '0 0 1 * *',
418 'weekly' => '0 0 * * 0',
419 'daily' => '0 0 * * *',
420 'midnight' => '0 0 * * *',
421 'hourly' => '0 * * * *',
424 if ( $cron =~ /^\@/ ) {
426 return $replace_at{ $cron };
429 for my $name ( keys %replace ) {
430 my $value = $replace{$name};
431 $cron =~ s/$name/$value/i;
432 last unless $cron =~ /\w/;
444 Catalyst::Plugin::Scheduler - Schedule events to run in a cron-like fashion
448 use Catalyst qw/Scheduler/;
450 # run remove_sessions in the Cron controller every hour
451 __PACKAGE__->schedule(
453 event => '/cron/remove_sessions'
456 # Run a subroutine at 4:05am every Sunday
457 __PACKAGE__->schedule(
462 # A long-running scheduled event that must be triggered
463 # manually by an authorized user
464 __PACKAGE__->schedule(
465 trigger => 'rebuild_search_index',
466 event => '/cron/rebuild_search_index',
468 $ wget -q http://www.myapp.com/?schedule_trigger=rebuild_search_index
472 This plugin allows you to schedule events to run at recurring intervals.
473 Events will run during the first request which meets or exceeds the specified
474 time. Depending on the level of traffic to the application, events may or may
475 not run at exactly the correct time, but it should be enough to satisfy many
476 basic scheduling needs.
480 Configuration is optional and is specified in MyApp->config->{scheduler}.
484 Set to 1 to enable logging of events as they are executed. This option is
485 enabled by default when running under -Debug mode. Errors are always logged
486 regardless of the value of this option.
490 The time zone of your system. This will be autodetected where possible, or
491 will default to UTC (GMT). You can override the detection by providing a
492 valid L<DateTime> time zone string, such as 'America/New_York'.
496 The current state of every event is stored in a file. By default this is
497 $APP_HOME/scheduler.state. This file is created on the first request if it
498 does not already exist.
502 The location of the optional YAML event configuration file. By default this
503 is $APP_HOME/scheduler.yml.
507 This option specifies IP addresses for trusted users. This option defaults
508 to 127.0.0.1. Multiple addresses can be specified by using an array
509 reference. This option is used for both events where auto_run is set to 0
510 and for manually-triggered events.
512 __PACKAGE__->config->{scheduler}->{hosts_allow} = '192.168.1.1';
513 __PACKAGE__->config->{scheduler}->{hosts_allow} = [
520 =head2 AUTOMATED EVENTS
522 Events are scheduled by calling the class method C<schedule>.
526 event => '/cron/remove_sessions',
529 package MyApp::Controller::Cron;
531 sub remove_sessions : Private {
532 my ( $self, $c ) = @_;
534 $c->delete_expired_sessions;
539 The time to run an event is specified using L<crontab(5)>-style syntax.
541 5 0 * * * # 5 minutes after midnight, every day
542 15 14 1 * * # run at 2:15pm on the first of every month
543 0 22 * * 1-5 # run at 10 pm on weekdays
544 5 4 * * sun # run at 4:05am every Sunday
553 month 0-12 (or names, see below)
554 day of week 0-7 (0 or 7 is Sun, or use names)
556 Instead of the first five fields, one of seven special strings may appear:
560 @yearly Run once a year, "0 0 1 1 *".
561 @annually (same as @yearly)
562 @monthly Run once a month, "0 0 1 * *".
563 @weekly Run once a week, "0 0 * * 0".
564 @daily Run once a day, "0 0 * * *".
565 @midnight (same as @daily)
566 @hourly Run once an hour, "0 * * * *".
570 The event to run at the specified time can be either a Catalyst private
571 action path or a coderef. Both types of event methods will receive the $c
572 object from the current request, but you must not rely on any request-specific
573 information present in $c as it will be from a random user request at or near
574 the event's specified run time.
576 Important: Methods used for events should be marked C<Private> so that
577 they can not be executed via the browser.
581 The auto_run parameter specifies when the event is allowed to be executed.
582 By default this option is set to 1, so the event will be executed during the
583 first request that matches the specified time in C<at>.
585 If set to 0, the event will only run when a request is made by a user from
586 an authorized address. The purpose of this option is to allow long-running
587 tasks to execute only for certain users.
591 event => '/cron/rebuild_search_index',
595 package MyApp::Controller::Cron;
597 sub rebuild_search_index : Private {
598 my ( $self, $c ) = @_;
600 # rebuild the search index, this may take a long time
603 Now, the search index will only be rebuilt when a request is made from a user
604 whose IP address matches the list in the C<hosts_allow> config option. To
605 run this event, you probably want to ping the app from a cron job.
607 0 0 * * * wget -q http://www.myapp.com/
611 To create an event that does not run on a set schedule and must be manually
612 triggered, you can specify the C<trigger> option instead of C<at>.
614 __PACKAGE__->schedule(
615 trigger => 'send_email',
616 event => '/events/send_email',
619 The event may then be triggered by a standard web request from an authorized
620 user. The trigger to run is specified by using a special GET parameter,
621 'schedule_trigger'; the path requested does not matter.
623 http://www.myapp.com/?schedule_trigger=send_email
625 By default, manual events may only be triggered by requests made from
626 localhost (127.0.0.1). To allow other addresses to run events, use the
627 configuration option L</hosts_allow>.
629 =head1 SCHEDULING USING A YAML FILE
631 As an alternative to using the schedule() method, you may define scheduled
632 events in an external YAML file. By default, the plugin looks for the
633 existence of a file called C<schedule.yml> in your application's home
634 directory. You can change the filename using the configuration option
637 Modifications to this file will be re-read once per minute during the normal
638 event checking process.
640 Here's an example YAML configuration file with 4 events. Each event is
641 denoted with a '-' character, followed by the same parameters used by the
642 C<schedule> method. Note that coderef events are not supported by the YAML
647 event: /cron/delete_sessions
648 - event: /cron/send_email
654 event: /cron/rebuild_search_index
658 All events are run inside of an eval container. This protects the user from
659 receiving any error messages or page crashes if an event fails to run
660 properly. All event errors are logged, even if logging is disabled.
662 =head1 PLUGIN SUPPORT
664 Other plugins may register scheduled events if they need to perform periodic
665 maintenance. Plugin authors, B<be sure to inform your users> if you do this!
666 Events should be registered from a plugin's C<setup> method.
672 if ( $c->can('schedule') ) {
682 The time at which an event will run is determined completely by the requests
683 made to the application. Apps with heavy traffic may have events run at very
684 close to the correct time, whereas apps with low levels of traffic may see
685 events running much later than scheduled. If this is a problem, you can use
686 a real cron entry that simply hits your application at the desired time.
688 0 * * * * wget -q http://www.myapp.com/
690 Events which consume a lot of time will slow the request processing for the
691 user who triggers the event. For these types of events, you should use
692 auto_run => 0 or manual event triggering.
696 The plugin only checks once per minute if any events need to be run, so the
697 overhead on each request is minimal. On my test server, the difference
698 between running with Scheduler and without was only around 0.02% (0.004
701 Of course, when a scheduled event runs, performance will depend on what's
702 being run in the event.
708 Schedule is a class method for adding scheduled events. See the
709 L<"/SCHEDULING"> section for more information.
711 =head2 scheduler_state
713 The current state of all scheduled events is available in an easy-to-use
714 format by calling $c->scheduler_state. You can use this data to build an
715 admin view into the scheduling engine, for example. This same data is also
716 displayed on the Catalyst debug screen.
718 This method returns an array reference containing a hash reference for each
723 'last_run' => '2005-12-29 16:29:33 EST',
727 'next_run' => '2005-12-30 00:00:00 EST',
728 'event' => '/cron/session_cleanup'
733 'next_run' => '2005-12-30 00:00:00 EST',
734 'event' => '/cron/build_rss'
738 =head1 INTERNAL METHODS
740 The following methods are extended by this plugin.
746 The main scheduling logic takes place during the dispatch phase.
750 On the Catalyst debug screen, all scheduled events are displayed along with
751 the next time they will be executed.
763 Andy Grundman, <andy@hybridized.org>
767 This program is free software, you can redistribute it and/or modify it
768 under the same terms as Perl itself.