Creare un Timer con le funzioni esterne delle librerie standard C "signal.h" e "time.h"

Da Gambas-it.org - Wikipedia.

Usando alcune funzioni esterne delle librerie standard C "signal.h" e "time.h", è possibile creare ed utilizzare un Timer

E' necessario avere installata nel sistema e richiamare in Gambas la libreria condivisa: "/usr/lib/x86_64-linux-gnu/libvlccore.so.9.0.0 " o altra, purché contenente le funzioni esterne "timer_create()", "timer_settime()" e "timer_delete()".

Mostriamo un esempio:

Private id As Long
Private num As Byte


Library "libc:6"

Private Const SIGALRM As Integer = 14      ' Alarm clock (POSIX)

' __sighandler_t signal (int __sig, __sighandler_t __handler)
' Set the handler for the signal SIG to HANDLER.
Private Extern signal(__sig As Integer, __handler As Pointer) As Pointer


Library "/usr/lib/x86_64-linux-gnu/libvlccore:9.0.0"

Public Struct timespec
  tv_sec As Long
  tv_nsec As Long
End Struct

Public Struct itimerspec
  it_interval As Struct Timespec
  it_value As Struct Timespec
End Struct

Private Enum CLOCK_REALTIME = 0, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, CLOCK_MONOTONIC_RAW,
             CLOCK_REALTIME_COARSE, CLOCK_MONOTONIC_COARSE, CLOCK_BOOTTIME, CLOCK_REALTIME_ALARM, CLOCK_BOOTTIME_ALARM

' int timer_create (clockid_t __clock_id, struct sigevent *__restrict __evp, timer_t *__restrict __timerid)
' Create new per-process timer using CLOCK_ID.
Private Extern timer_create(__clock_id As Integer, __evp As Pointer, __timerid As Pointer) As Integer

' int timer_settime (timer_t __timerid, int __flags, const struct itimerspec *__restrict __value, struct itimerspec *__restrict __ovalue)
' Set timer TIMERID to VALUE, returning old value in OVALUE.
Private Extern timer_settime(__timerid As Long, __flags As Integer, __value As Itimerspec, __ovalue As Itimerspec) As Integer

' int timer_delete (timer_t __timerid)
' Delete timer TIMERID.
Private Extern timer_delete(__timerid As Long) As Integer


Public Sub Main()
  
  signal(SIGALRM, timer_callback)
  
  Start_Timer(300000000)
  
  While num < 99
    Sleep 0.01
  Wend
   
  Stop_Timer()
   
  timer_delete(id)
  
End

Private Procedure Start_Timer(vlr As Long)
 
 Dim spec As New Itimerspec
   
  With spec
    .it_value.tv_sec = 0
    .it_value.tv_nsec = vlr     ' Attende 300.000.000 di nanosecondi prima di inviare un segnale Timer
    .it_interval.tv_sec = 0
    .it_interval.tv_nsec = vlr  ' Invia un segnale Timer ogni 300.000.000 nanosecondi
  End With
  
  timer_create(CLOCK_REALTIME, 0, VarPtr(id))
  timer_settime(id, 0, spec, Null)
 
End
  
Private Procedure timer_callback(signum As Integer)
 
 Print num; "   Intercettato segnale Timer: "; signum
 
 Inc num
 
End

Private Procedure Stop_Timer()
 
 Dim spec As New Itimerspec

 With spec
   .it_value.tv_sec = 0
   .it_value.tv_nsec = 0
   .it_interval.tv_sec = 0
   .it_interval.tv_nsec = 0
 End With
  
 timer_settime(id, 0, spec, Null)
 timer_delete(id)
  
End


Riferimenti