in reply to Run subroutine occasionally
The yield function in MCE::Child (ditto for MCE::Hobo) retains interval periods; i.e. do something at/near every N fractional seconds. It works quite well, even among many workers.
use strict; use warnings; use MCE::Child; use Time::HiRes qw(sleep time); STDOUT->autoflush(1); # do something periodically in the background my $child = MCE::Child->create(sub { while (1) { MCE::Child->yield(300.0); print "Inside child ", time, $/; } }); # application code print "Parent", $/; # reap child $child->kill; $child->join;
Demonstration
Notice the output for the next demonstration where the child displays output every 0.2 seconds, even simulating work. It does a delta behind the scene from the last yield statement in order to retain near/exact intervals.
use strict; use warnings; use MCE::Child; use Time::HiRes qw(sleep time); STDOUT->autoflush(1); my $child = MCE::Child->create(sub { while (1) { MCE::Child->yield(0.200); print "Inside child ", time, $/; sleep 0.1; # simulate work } }); for (1..5) { print "Parent ", $_, $/; sleep 1; } $child->kill; $child->join;
Output
$ perl demo.pl Parent 1 Inside child 1646249559.98288 Inside child 1646249560.18285 Inside child 1646249560.38241 Inside child 1646249560.58239 Parent 2 Inside child 1646249560.78239 Inside child 1646249560.98283 Inside child 1646249561.18284 Inside child 1646249561.38284 Inside child 1646249561.58284 Inside child 1646249561.7825 Parent 3 Inside child 1646249561.98284 Inside child 1646249562.18284 Inside child 1646249562.38284 Inside child 1646249562.58284 Inside child 1646249562.78284 Parent 4 Inside child 1646249562.98284 Inside child 1646249563.18284 Inside child 1646249563.38284 Inside child 1646249563.58284 Inside child 1646249563.78283 Parent 5 Inside child 1646249563.98284 Inside child 1646249564.18284 Inside child 1646249564.38284 Inside child 1646249564.58284 Inside child 1646249564.78284
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Run subroutine occasionally
by marioroy (Prior) on Mar 03, 2022 at 03:19 UTC |