NAME
Proc::tored - manage a process using a pid file
SYNOPSIS
my $proctor = Proc::tored->new(dir => '/tmp', name => 'my-service');
# Call do_stuff while the service is running or until do_stuff returns false
$proctor->service(\&do_stuff)
or die sprintf('process %d is already running this service!', $proctor->running_pid);
# Signal another process running this service to quit gracefully, throwing an
# error if it does not self-terminate after 15 seconds.
if (my $pid = $proctor->stop_running_process(15)) {
die "process $pid is being stubborn!";
}
DESCRIPTION
METHODS
new
Creates a new service object, which can be used to run the service and/or signal another process to quit. The pid file is not created or accessed by this method.
- dir
-
A valid directory path where the pid file is to be created or an existing pid file is to be found.
- name
-
The file name to be used when creating or accessing the service's associated pid file.
- poll_wait_time
path
Returns the file system path created by concatenating the values of dir
and name
that were passed to new
.
is_running
See "is_running" in Proc::tored::Role::Running.
service
Accepts a code ref which will be called repeatedly until it or "is_running" return false. While the service is running, a SIGTERM
handler is installed. When a SIGTERM
is received, "is_running" will be set to false and service loop will self-terminate.
Note that it is possible for a signal to arrive between the "is_running" check and the execution of the code ref. If this is a concern for the caller, it is recommended that the code ref avoid blocking for long periods, such as extended sleep
times or long-running database queries which perl cannot interrupt.
Example using a pool of forked workers, an imaginary task queue, and a secondary condition that decides whether to stop running (aside from the built-in SIGTERM
handler):
$proctor->service(sub {
# Wait for an available worker, but with a timeout
my $worker = $worker_pool->next_available(0.1);
if ($worker) {
# Pull next task from the queue with a 0.1s timeout
my $task = poll_queue_with_timeout(0.1);
if ($task) {
$worker->assign($task);
}
}
return unless touch_file_exists();
return 1;
});
running_pid
Returns the pid identified in the pid file. Returns 0 if the pid file does not exist or is empty.
stop_running_process
See "stop_running_process" in Proc::tored::Role::Running. When called from this class, the $pid
parameter is provided via "running_pid".
run_lock
Attempts to atomically acquire the run lock. Once held, the pid file is created (if needed) and the current process' pid is written to it, "is_running" will return true and a SIGTERM
handler will be active. Existing handlers will be executed after the one assigned for the run lock.
If the lock is acquired, a Guard object is returned that will release the lock once out of scope. Returns undef otherwise.
"service" is preferred to this method for most uses.