C based timer: Difference between revisions

From SoftwareGuy
Jump to navigation Jump to search
Mark (talk | contribs)
Mark (talk | contribs)
 
(7 intermediate revisions by the same user not shown)
Line 1: Line 1:
= C Timer =
= C Timer =


<code>#include <iostream>
<code>
#include <unistd.h>
#include <iostream>
<using namespace std;</code>
#include <unistd.h>
 
using namespace std;
// Define the callback function</code>
 
// Define the callback function
void callback() {</code>
 
void callback() {
cout << "Timer callback called!" << endl;</code>
  cout << "Timer callback called!" << endl;
 
}
<code>}</code>
 
// Create the timer
''<code>// Create the timer</code>''
timer_t timer;
 
struct sigevent sigev;
<code>timer_t timer;</code>
// Set up the timer
 
<code>struct sigevent sigev;</code>
sigev.sigev_notify = SIGEV_THREAD;
 
sigev.sigev_notify_function = callback;
''<code>// Set up the timer</code>''
sigev.sigev_value.sival_ptr = &timer;
 
<code>sigev.sigev_notify = SIGEV_THREAD;</code>
timer_create(CLOCK_REALTIME, &sigev, &timer);
 
// Start the timer
<code>sigev.sigev_notify_function = callback;</code>
timer_settime(timer, 0, new itimerspec{1, 0}, NULL);
 
// Wait for the timer to expire
<code>sigev.sigev_value.sival_ptr = &timer;</code>
pause();
 
// Delete the timer
<code>timer_create(CLOCK_REALTIME, &sigev, &timer);</code>
timer_delete(timer);
 
</code>
''<code>// Start the timer</code>''
 
<code>timer_settime(timer, 0, new itimerspec{1, 0}, NULL);</code>
 
''<code>// Wait for the timer to expire</code>''
 
<code>pause();</code>
 
''<code>// Delete the timer</code>''
 
<code>timer_delete(timer);</code>


= Python timer =
= Python timer =
<code>import threading, time, signal
<code>
 
import threading, time, signal
from datetime import timedelta
 
from datetime import timedelta
WAIT_TIME_SECONDS = 1
 
WAIT_TIME_SECONDS = 1
class ProgramKilled(Exception):
    pass
class ProgramKilled(Exception):
def foo():
    pass
    print time.ctime()
def foo():
def signal_handler(signum, frame):
    print time.ctime()
    raise ProgramKilled
def signal_handler(signum, frame):
class Job(threading.Thread):
    raise ProgramKilled
    def __init__(self, interval, execute, *args, **kwargs):
class Job(threading.Thread):
        threading.Thread.__init__(self)
    def __init__(self, interval, execute, *args, **kwargs):
        self.daemon = False
        threading.Thread.__init__(self)
        self.stopped = threading.Event()
        self.daemon = False
        self.interval = interval
        self.stopped = threading.Event()
        self.execute = execute
        self.interval = interval
        self.args = args
        self.execute = execute
        self.kwargs = kwargs
        self.args = args
       
        self.kwargs = kwargs
    def stop(self):
       
                self.stopped.set()
    def stop(self):
                self.join()
        self.stopped.set()
        self.join()
     def run(self):
     def run(self):
            while not self.stopped.wait(self.interval.total_seconds()):
        while not self.stopped.wait(self.interval.total_seconds()):
                self.execute(*self.args, **self.kwargs)
            self.execute(*self.args, **self.kwargs)
if __name__ == "__main__":
if __name__ == "__main__":
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)
    job = Job(interval=timedelta(seconds=WAIT_TIME_SECONDS), execute=foo)
    job = Job(interval=timedelta(seconds=WAIT_TIME_SECONDS), execute=foo)
    job.start()
    job.start()
      
      
    while True:
    while True:
          try:
          try:
              time.sleep(1)
              time.sleep(1)
          except ProgramKilled:
          except ProgramKilled:
              print "Program killed: running cleanup code"
              print "Program killed: running cleanup code"
              job.stop()
              job.stop()
              break
              break
</code>
</code>
#output
#output
Line 91: Line 81:
==== More examples ====
==== More examples ====
<code>
<code>
import datetime, threading, time
import datetime, threading, time
next_call = time.time()
def foo():
next_call = time.time()
global next_call
print datetime.datetime.now()
def foo():
next_call = next_call+1
    global next_call
threading.Timer( next_call - time.time(), foo ).start()
    print datetime.datetime.now()
 
    next_call = next_call+1
foo()
    threading.Timer( next_call - time.time(), foo ).start()
foo()
</code>
</code>
----
----
<code>import datetime, threading, time</code>
<code>
 
import datetime, threading, time
 
<code>def foo():</code>
def foo():
 
    next_call = time.time()
<code>next_call = time.time()</code>
    while True:
 
        print datetime.datetime.now()         
<code>while True:</code>
        next_call = next_call+1;
 
time.sleep(next_call - time.time())
<code>print datetime.datetime.now()</code>        
 
timerThread = threading.Thread(target=foo)
 
timerThread.start()</code>
<code>next_call = next_call+1;</code>
 
<code>time.sleep(next_call - time.time())</code>
 
 
<code>timerThread = threading.Thread(target=foo)</code>
 
<code>timerThread.start()</code>


Followed by:
Followed by:


<code>timerThread = threading.Thread(target=foo)</code>
<code>
 
timerThread = threading.Thread(target=foo)
<code>timerThread.daemon = True</code>
timerThread.daemon = True
 
timerThread.start()</code>
<code>timerThread.start()</code>
----
----<code>import threading</code>
<code>
 
import threading
 
def work ():
<code>def work ():</code>
    threading.Timer(0.25, work).start ()
 
    print "stackoverflow"
<code>threading.Timer(0.25, work).start ()</code>
work ()
 
</code>
<code>print "stackoverflow"</code>
----
 
<code>
 
import threading
<code>work ()</code>
def do_every (interval, worker_func, iterations = 0):
----<code>import threading</code>
  if iterations != 1:
 
    threading.Timer (
<code>def do_every (interval, worker_func, iterations = 0):</code>
      interval,
 
      do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1]
<code>if iterations != 1:</code>
    ).start ()
 
  worker_func ()
<code>threading.Timer (</code>
def print_hw ():
 
  print "hello world"
<code>interval,</code>
def print_so ():
 
  print "stackoverflow"
<code>do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1]</code>
# call print_so every second, 5 times total
 
do_every (1, print_so, 5)
<code>).start ()</code> 
# call print_hw two times per second, forever
 
do_every (0.5, print_hw)
 
</code>
<code>worker_func ()</code>
 
<code>def print_hw ():</code>
 
<code>print "hello world"</code>
 
 
<code>def print_so ():</code>
 
<code>print "stackoverflow"</code>
 
 
 
<code># call print_so every second, 5 times total</code>
 
<code>do_every (1, print_so, 5)</code>
 
 
<code># call print_hw two times per second, forever</code>
 
<code>do_every (0.5, print_hw)</code>
----
----

Latest revision as of 15:34, 1 April 2024

C Timer[edit | edit source]

#include <iostream>
#include <unistd.h>
using namespace std;

// Define the callback function

void callback() {
  cout << "Timer callback called!" << endl;
}

// Create the timer
timer_t timer;
struct sigevent sigev;
// Set up the timer

sigev.sigev_notify = SIGEV_THREAD;
sigev.sigev_notify_function = callback;
sigev.sigev_value.sival_ptr = &timer;

timer_create(CLOCK_REALTIME, &sigev, &timer);
// Start the timer
timer_settime(timer, 0, new itimerspec{1, 0}, NULL);
// Wait for the timer to expire
pause();
// Delete the timer
timer_delete(timer);

Python timer[edit | edit source]

import threading, time, signal

from datetime import timedelta

WAIT_TIME_SECONDS = 1

class ProgramKilled(Exception):
    pass
def foo():
    print time.ctime()
def signal_handler(signum, frame):
    raise ProgramKilled
class Job(threading.Thread):
    def __init__(self, interval, execute, *args, **kwargs):
        threading.Thread.__init__(self)
        self.daemon = False
        self.stopped = threading.Event()
        self.interval = interval
        self.execute = execute
        self.args = args
        self.kwargs = kwargs
        
    def stop(self):
        self.stopped.set()
        self.join()
   def run(self):
        while not self.stopped.wait(self.interval.total_seconds()):
            self.execute(*self.args, **self.kwargs)
if __name__ == "__main__":
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)
    job = Job(interval=timedelta(seconds=WAIT_TIME_SECONDS), execute=foo)
    job.start()
   
    while True:
          try:
              time.sleep(1)
          except ProgramKilled:
              print "Program killed: running cleanup code"
              job.stop()
              break

  1. output
  2. Tue Oct 16 17:47:51 2018
  3. Tue Oct 16 17:47:52 2018
  4. Tue Oct 16 17:47:53 2018

More examples[edit | edit source]

import datetime, threading, time

next_call = time.time()

def foo():
    global next_call
    print datetime.datetime.now()
    next_call = next_call+1
    threading.Timer( next_call - time.time(), foo ).start()

foo()


import datetime, threading, time

def foo():
    next_call = time.time()
    while True:
        print datetime.datetime.now()        
        next_call = next_call+1;
time.sleep(next_call - time.time())

timerThread = threading.Thread(target=foo)
timerThread.start()

Followed by:

timerThread = threading.Thread(target=foo)
timerThread.daemon = True
timerThread.start()

import threading
def work ():
    threading.Timer(0.25, work).start ()
    print "stackoverflow"
work ()


import threading
def do_every (interval, worker_func, iterations = 0):
 if iterations != 1:
   threading.Timer (
     interval,
     do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1]
   ).start ()
 worker_func ()
def print_hw ():
 print "hello world"
def print_so ():
 print "stackoverflow"
# call print_so every second, 5 times total
do_every (1, print_so, 5)
# call print_hw two times per second, forever
do_every (0.5, print_hw)