# Simple cron-like component.
# Implements a recurring event generator that
# accepts commands through proxy object methods.
# Copyright 2004 by Rocco Caputo.  Free software.
# Same terms as Perl itself.  Have fun!

# The ChronicObject class implements a proxy
# object facade over ChronicMessages.  The latter
# class is a singleton recurring events service.

package ChronicObject;

use warnings;
use strict;

use POE;
use ChronicMessages;

# Start the singleton messaging service.  Make
# addressing it convenient by giving the current
# class' name as its alias.

ChronicMessages->spawn(Alias => __PACKAGE__);

my $chronic_id = 0;

# Create a new proxy object.  Start the callback
# timer, and return an object representing it.

sub new {
  my ($class, %param) = @_;

  $poe_kernel->post(
    __PACKAGE__, start => {
      Name => ++$chronic_id,
      %param,
    }
  );

  my $self = bless { MyID => $chronic_id }, $class;
  return $self;
}

# Ensure that event generators are stopped when
# their proxies are destroyed.

sub DESTROY {
  my $self = shift;
  $self->stop();
}

# Explicitly stop a recurring event generator.

sub stop {
  my $self = shift;
  return unless $self->{MyID};

  $poe_kernel->post(
    __PACKAGE__, stop => {
      Name => $self->{MyID},
    }
  );

  delete $self->{MyID};
}

1;
