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.


In reply to Re: Call function no more than every 0.1 seconds by haukex
in thread Call function no more than every 0.1 seconds by zapoi

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.