transiency has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, So I've been having this problem where I am sampling something (say temperature) but the rate at which i want to sample needs to be variable. I setup an entry box so the user can enter the desired time, and start stop and restart buttons. Everything works great the first time through, set the timer to 2000, and it samples every 2 seconds. Stop and restart work as well. But if i try and change the value and sample again, it yields erratic behavior. It looks like it might be creating another instance of the repeat. Any ideas on what I am doing wrong? Thank you for you time.
#!/usr/bin/perl use Tk; use strict; use warnings; use subs qw/samp destruct restartsamp/; my $mw = MainWindow->new; $mw->minsize(400,300); $mw->maxsize(1024,768); my $srate; my $dosample = 1; my $smpratelbl = $mw->Label(-text=> "Enter Sample Rate [msec]"); my $smprate = $mw->Entry(-textvariable=>\$srate); my $startsmp = $mw->Button(-text => "Sample/Change Rate", -command => sub{my $smp = $mw->repeat( +$srate, \&samp)}); my $stopsmp = $mw->Button(-text => "Stop Sampling", -command => \&destruct); my $restartsmp = $mw->Button(-text => "Restart Sampling", -command => \&restartsamp); $smpratelbl->pack; $smprate->pack; $startsmp->pack; $restartsmp->pack; $stopsmp->pack; MainLoop; sub destruct(){ $dosample = 0; } sub restartsamp(){ $dosample = 1; } sub samp(){ my $temp1; if($dosample == 1){ my $temp1 = localtime; print "$temp1 $srate\n"; my $temp2 = "$temp1 " . "$srate\n"; } }
foreach(@the_wicked){sleep(0);}

Replies are listed 'Best First'.
Re: Tk::Repeat - Variable Rate?
by ~~David~~ (Hermit) on Mar 30, 2009 at 22:32 UTC
    You need to cancel your previous signal before you create the new one..
    my $startsmp = $mw->Button(-text => "Sample/Change Rate", -command => sub{ if ( not defined $smp ){ $ +smp = $mw->repeat($srate, \&samp)} else { $smp->cancel; $smp = $mw->repeat($sr +ate, \&samp) } } );
      Thank you david :)

      That is exactly what i was missing, fixes everything. I'm rather new to Tk, so excuse my ignorance :)

      Thanks again!
      foreach(@the_wicked){sleep(0);}