From 159600b6694095ea81c0c0ddf6590c970fbc8b5c Mon Sep 17 00:00:00 2001 From: Elijah Perrault Date: Fri, 21 Jan 2011 14:15:52 -0700 Subject: [PATCH] Added timer_add() and timer_del() to API::Std for timers. --- bin/auto | 25 ++++++++++++++++++++++--- doc/CHANGELOG | 1 + src/API/Std.pm | 42 +++++++++++++++++++++++++++++++++++++++++- 3 files changed, 64 insertions(+), 4 deletions(-) diff --git a/bin/auto b/bin/auto index 3b8ed20..3dd3353 100755 --- a/bin/auto +++ b/bin/auto @@ -77,7 +77,7 @@ API::Std::event_add("on_sighup"); # Print startup message. println "* ".NAME." (version ".VER.".".SVER.".".REV.RSTAGE.") is starting up..."; -our ($PID); +our ($PID, %TIMERS); # Check for debug mode. our $DEBUG = 0; @@ -208,8 +208,27 @@ else { } undef $it; -# Keep Auto alive. -while (1) { sleep 1; } +# Check timers. +while (1) { + foreach my $tk (keys %TIMERS) { + if ($TIMERS{$tk}{time} <= time) { + &{ $TIMERS{$tk}{sub} }(); + if ($TIMERS{$tk}{type} == 1) { + # If it's type 1, delete from memory. + delete $TIMERS{$tk}; + } + elsif ($TIMERS{$tk}{type} == 2) { + # If it's type 2, reset timer. + $TIMERS{$tk}{time} = time + $TIMERS{$tk}{secs}; + } + else { + # This should never happen. + delete $TIMERS{$tk}; + } + } + } + sleep 1; +} ############### # Subroutines # diff --git a/doc/CHANGELOG b/doc/CHANGELOG index f22e7f0..c716b87 100644 --- a/doc/CHANGELOG +++ b/doc/CHANGELOG @@ -3,6 +3,7 @@ Auto IRC Bot 3.0: Change Log 3.0 Indev ================================================================== + * Added timer_add() and timer_del() to API::Std for timers. * Added events: on_sigterm, on_sigint and on_sighup. * Added event_add|del|run() and hook_add|del() to API::Std for managing and running events/hooks. diff --git a/src/API/Std.pm b/src/API/Std.pm index 3f95a4b..013bdbf 100644 --- a/src/API/Std.pm +++ b/src/API/Std.pm @@ -9,7 +9,7 @@ use warnings; use Exporter; our @ISA = qw(Exporter); -our @EXPORT_OK = qw(conf_get trans err awarn); +our @EXPORT_OK = qw(conf_get trans err awarn timer_add timer_del); my (%LANGE, %MODULE, %EVENTS, %HOOKS); @@ -179,6 +179,46 @@ sub hook_del } } +# Add a timer to Auto. +sub timer_add +{ + my ($name, $type, $time, $sub) = @_; + $name = lc($name); + + # Check for invalid type/time. + if ($type =~ m/[^1-2]/) { + return 0; + } + if ($time =~ m/[^0-9]/) { + return 0; + } + + unless (defined $Auto::TIMERS{$name}) { + $Auto::TIMERS{$name}{type} = $type; + $Auto::TIMERS{$name}{time} = time + $time; + $Auto::TIMERS{$name}{secs} = $time if ($type == 2); + $Auto::TIMERS{$name}{sub} = $sub; + return 1; + } + else { + return 0; + } +} + +# Delete a timer from Auto. +sub timer_del +{ + my ($name) = @_; + $name = lc($name); + + if (defined $Auto::TIMERS{$name}) { + delete $Auto::TIMERS{$name}; + return 1; + } + + return 0; +} + # Configuration value getter. sub conf_get {