Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Call function no more than every 0.1 seconds

by haukex (Archbishop)
on Aug 12, 2020 at 20:12 UTC ( [id://11120664]=note: print w/replies, xml ) Need Help??


in reply to Call function no more than every 0.1 seconds

From "The most precise second (timer)", which choroba linked to, see my post here which demonstrates clock_nanosleep from Time::HiRes.

You don't mention what's supposed to happen when your function happens to take longer to execute than 0.1 seconds?

use warnings; use strict; use Time::HiRes qw/ clock_gettime clock_nanosleep CLOCK_REALTIME TIMER_ABSTIME /; die "Don't have nanosleep" unless Time::HiRes::d_nanosleep(); use Time::HiRes qw/usleep/; # just for this fake "myfunc" sub myfunc { printf "fired %.2f\n", clock_gettime(CLOCK_REALTIME); my $delay_us = int(rand 100000)+10000; # 110000us = 0.11s printf "delay %.2fs\n", $delay_us/1e6; usleep $delay_us; } my $next_s = int(clock_gettime(CLOCK_REALTIME))+1; my $interval_s = 0.1; my $run = 1; $SIG{INT} = sub { $run = 0 }; while ($run) { my $now_s = clock_gettime(CLOCK_REALTIME); $next_s += $interval_s while $next_s < $now_s; clock_nanosleep(CLOCK_REALTIME, $next_s*1e9, TIMER_ABSTIME); myfunc(); }

Update: Note that since the above code uses floating-point numbers there's a small chance for errors there. If that's a concern, you can switch to nanoseconds, since that's what clock_nanosleep takes anway.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11120664]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (8)
As of 2024-04-19 08:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found