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/;
15 our $VERSION = '0.01';
17 __PACKAGE__->mk_classdata( '_events' => [] );
18 __PACKAGE__->mk_accessors('_event_state');
21 my ( $class, %args ) = @_;
23 unless ( $args{event} ) {
24 Catalyst::Exception->throw(
25 message => 'The schedule method requires an event parameter' );
28 my $conf = $class->config->{scheduler};
31 trigger => $args{trigger},
32 event => $args{event},
33 auto_run => ( defined $args{auto_run} ) ? $args{auto_run} : 1,
38 # replace keywords that Set::Crontab doesn't support
39 $args{at} = _prepare_cron( $args{at} );
41 # parse the cron entry into a DateTime::Set
43 eval { $set = DateTime::Event::Cron->from_cron( $args{at} ) };
45 Catalyst::Exception->throw(
46 "Scheduler: Unable to parse 'at' value "
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}
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} = [];
120 # do not allow the event to modify the response
121 local $c->res->{body};
122 local $c->res->{cookies};
123 local $c->res->{headers};
124 local $c->res->{location};
125 local $c->res->{status};
127 if ( ref $event->{event} eq 'CODE' ) {
128 $event->{event}->($c);
131 $c->forward( $event->{event} );
134 my @errors = @{ $c->{error} };
135 push @errors, $@ if $@;
138 'Scheduler: Error executing ' . "$event_name: $_" )
142 $c->_mark_finished($event);
150 # initial configuration
151 $c->config->{scheduler}->{logging} ||= ( $c->debug ) ? 1 : 0;
152 $c->config->{scheduler}->{time_zone} ||= $c->_detect_timezone();
153 $c->config->{scheduler}->{state_file} ||= $c->path_to('scheduler.state');
154 $c->config->{scheduler}->{hosts_allow} ||= '127.0.0.1';
155 $c->config->{scheduler}->{yaml} ||= $c->path_to('scheduler.yml');
160 # check and reload the YAML file with schedule data
164 # each process needs to load the YAML file independently
165 if ( $c->_event_state->{yaml_mtime}->{$$} ||= 0 ) {
166 return if ( time - $c->_event_state->{last_check} < 60 );
169 return unless -e $c->config->{scheduler}->{yaml};
172 my $mtime = ( stat $c->config->{scheduler}->{yaml} )->mtime;
173 if ( $mtime > $c->_event_state->{yaml_mtime}->{$$} ) {
174 $c->_event_state->{yaml_mtime}->{$$} = $mtime;
175 $c->_save_event_state();
177 # wipe out all current events and reload from YAML
180 my $yaml = YAML::LoadFile( $c->config->{scheduler}->{yaml} );
182 foreach my $event ( @{$yaml} ) {
183 $c->schedule( %{$event} );
186 $c->log->info( "Scheduler: PID $$ loaded "
188 . ' events from YAML file' )
189 if $c->config->{scheduler}->{logging};
193 $c->log->error("Error reading YAML file: $@");
197 # Detect the current time zone
198 sub _detect_timezone {
202 eval { $tz = DateTime::TimeZone->new( name => 'local' ) };
205 'Scheduler: Unable to autodetect local time zone, using UTC');
210 'Scheduler: Using autodetected time zone: ' . $tz->name )
211 if $c->config->{scheduler}->{logging};
216 # Check for authorized users on non-auto events
217 sub _event_authorized {
220 # this should never happen, but just in case...
221 return unless $c->req->address;
223 my $hosts_allow = $c->config->{scheduler}->{hosts_allow};
224 $hosts_allow = [$hosts_allow] unless ref($hosts_allow) eq 'ARRAY';
226 my $ip = Set::Object->new( [ $c->req->address ] );
227 my $allowed = Set::Object->new( $hosts_allow );
229 return $ip->subset($allowed);
232 # get the state from the state file
233 sub _get_event_state {
236 if ( -e $c->config->{scheduler}->{state_file} ) {
238 lock_retrieve $c->config->{scheduler}->{state_file} );
242 # initialize the state file
244 { last_check => time,
248 $c->_save_event_state();
252 # Check the state file to ensure we are the only process running an event
254 my ( $c, $event ) = @_;
256 $c->_get_event_state();
258 return if $c->_event_state->{ $event->{event} };
260 # this is a 2-step process to prevent race conditions
261 # 1. write the state file with our PID
262 $c->_event_state->{ $event->{event} } = $$;
263 $c->_save_event_state();
265 # 2. re-read the state file and make sure it's got the same PID
266 $c->_get_event_state();
267 if ( $c->_event_state->{ $event->{event} } == $$ ) {
274 # Mark an event as finished
276 my ( $c, $event ) = @_;
278 $c->_event_state->{ $event->{event} } = 0;
279 $c->_save_event_state();
282 # update the state file on disk
283 sub _save_event_state {
286 lock_store $c->_event_state, $c->config->{scheduler}->{state_file};
289 # Set::Crontab does not support day names, or '@' shortcuts
293 return $cron unless $cron =~ /\w/;
317 'yearly' => '0 0 1 1 *',
318 'annually' => '0 0 1 1 *',
319 'monthly' => '0 0 1 * *',
320 'weekly' => '0 0 * * 0',
321 'daily' => '0 0 * * *',
322 'midnight' => '0 0 * * *',
323 'hourly' => '0 * * * *',
326 for my $name ( keys %replace ) {
327 my $value = $replace{$name};
329 if ( $cron =~ /^\@$name/ ) {
334 $cron =~ s/$name/$value/i;
335 last unless $cron =~ /\w/;
349 Catalyst::Plugin::Scheduler - Schedule events to run in a cron-like fashion
353 use Catalyst qw/Scheduler/;
355 # run remove_sessions in the Cron controller every hour
356 __PACKAGE__->schedule(
358 event => '/cron/remove_sessions'
361 # Run a subroutine at 4:05am every Sunday
362 __PACKAGE__->schedule(
367 # A long-running scheduled event that must be triggered
368 # manually by an authorized user
369 __PACKAGE__->schedule(
370 trigger => 'rebuild_search_index',
371 event => '/cron/rebuild_search_index',
373 $ wget -q http://www.myapp.com/?schedule_trigger=rebuild_search_index
377 This plugin allows you to schedule events to run at recurring intervals.
378 Events will run during the first request which meets or exceeds the specified
379 time. Depending on the level of traffic to the application, events may or may
380 not run at exactly the correct time, but it should be enough to satisfy many
381 basic scheduling needs.
385 Configuration is optional and is specified in MyApp->config->{scheduler}.
389 Set to 1 to enable logging of events as they are executed. This option is
390 enabled by default when running under -Debug mode. Errors are always logged
391 regardless of the value of this option.
395 The time zone of your system. This will be autodetected where possible, or
396 will default to UTC (GMT). You can override the detection by providing a
397 valid L<DateTime> time zone string, such as 'America/New_York'.
401 The current state of every event is stored in a file. By default this is
402 $APP_HOME/scheduler.state. This file is created on the first request if it
403 does not already exist.
407 The location of the optional YAML event configuration file. By default this
408 is $APP_HOME/scheduler.yml.
412 This option specifies IP addresses for trusted users. This option defaults
413 to 127.0.0.1. Multiple addresses can be specified by using an array
414 reference. This option is used for both events where auto_run is set to 0
415 and for manually-triggered events.
417 __PACKAGE__->config->{scheduler}->{hosts_allow} = '192.168.1.1';
418 __PACKAGE__->config->{scheduler}->{hosts_allow} = [
425 =head2 AUTOMATED EVENTS
427 Events are scheduled by calling the class method C<schedule>.
431 event => '/cron/remove_sessions',
434 package MyApp::Controller::Cron;
436 sub remove_sessions : Private {
437 my ( $self, $c ) = @_;
439 $c->delete_expired_sessions;
444 The time to run an event is specified using L<crontab(5)>-style syntax.
446 5 0 * * * # 5 minutes after midnight, every day
447 15 14 1 * * # run at 2:15pm on the first of every month
448 0 22 * * 1-5 # run at 10 pm on weekdays
449 5 4 * * sun # run at 4:05am every Sunday
458 month 0-12 (or names, see below)
459 day of week 0-7 (0 or 7 is Sun, or use names)
461 Instead of the first five fields, one of seven special strings may appear:
465 @yearly Run once a year, "0 0 1 1 *".
466 @annually (same as @yearly)
467 @monthly Run once a month, "0 0 1 * *".
468 @weekly Run once a week, "0 0 * * 0".
469 @daily Run once a day, "0 0 * * *".
470 @midnight (same as @daily)
471 @hourly Run once an hour, "0 * * * *".
475 The event to run at the specified time can be either a Catalyst private
476 action path or a coderef. Both types of event methods will receive the $c
477 object from the current request, but you must not rely on any request-specific
478 information present in $c as it will be from a random user request at or near
479 the event's specified run time.
481 Important: Methods used for events should be marked C<Private> so that
482 they can not be executed via the browser.
486 The auto_run parameter specifies when the event is allowed to be executed.
487 By default this option is set to 1, so the event will be executed during the
488 first request that matches the specified time in C<at>.
490 If set to 0, the event will only run when a request is made by a user from
491 an authorized address. The purpose of this option is to allow long-running
492 tasks to execute only for certain users.
496 event => '/cron/rebuild_search_index',
500 package MyApp::Controller::Cron;
502 sub rebuild_search_index : Private {
503 my ( $self, $c ) = @_;
505 # rebuild the search index, this may take a long time
508 Now, the search index will only be rebuilt when a request is made from a user
509 whose IP address matches the list in the C<hosts_allow> config option. To
510 run this event, you probably want to ping the app from a cron job.
512 0 0 * * * wget -q http://www.myapp.com/
516 To create an event that does not run on a set schedule and must be manually
517 triggered, you can specify the C<trigger> option instead of C<at>.
519 __PACKAGE__->schedule(
520 trigger => 'send_email',
521 event => '/events/send_email',
524 The event may then be triggered by a standard web request from an authorized
525 user. The trigger to run is specified by using a special GET parameter,
526 'schedule_trigger'; the path requested does not matter.
528 http://www.myapp.com/?schedule_trigger=send_email
530 By default, manual events may only be triggered by requests made from
531 localhost (127.0.0.1). To allow other addresses to run events, use the
532 configuration option L</hosts_allow>.
534 =head1 SCHEDULING USING A YAML FILE
536 As an alternative to using the schedule() method, you may define scheduled
537 events in an external YAML file. By default, the plugin looks for the
538 existence of a file called C<schedule.yml> in your application's home
539 directory. You can change the filename using the configuration option
542 Modifications to this file will be re-read once per minute during the normal
543 event checking process.
545 Here's an example YAML configuration file with 4 events. Each event is
546 denoted with a '-' character, followed by the same parameters used by the
547 C<schedule> method. Note that coderef events are not supported by the YAML
552 event: /cron/delete_sessions
553 - event: /cron/send_email
559 event: /cron/rebuild_search_index
563 All events are run inside of an eval container. This protects the user from
564 receiving any error messages or page crashes if an event fails to run
565 properly. All event errors are logged, even if logging is disabled.
567 =head1 PLUGIN SUPPORT
569 Other plugins may register scheduled events if they need to perform periodic
570 maintenance. Plugin authors, B<be sure to inform your users> if you do this!
571 Events should be registered from a plugin's C<setup> method.
577 if ( $c->can('schedule') ) {
587 The time at which an event will run is determined completely by the requests
588 made to the application. Apps with heavy traffic may have events run at very
589 close to the correct time, whereas apps with low levels of traffic may see
590 events running much later than scheduled. If this is a problem, you can use
591 a real cron entry that simply hits your application at the desired time.
593 0 * * * * wget -q http://www.myapp.com/
595 Events which consume a lot of time will slow the request processing for the
596 user who triggers the event. For these types of events, you should use
597 auto_run => 0 or manual event triggering.
601 The plugin only checks once per minute if any events need to be run, so the
602 overhead on each request is minimal. On my test server, the difference
603 between running with Scheduler and without was only around 0.02% (0.004
606 Of course, when a scheduled event runs, performance will depend on what's
607 being run in the event.
615 Andy Grundman, <andy@hybridized.org>
619 This program is free software, you can redistribute it and/or modify it
620 under the same terms as Perl itself.