Recently, timer was used in JNI pure C development for Android. If it is too slow to go from Java, I want to use the Linux API to find two implementations:
1:
Struct itimerval tick;
Int ret = 0;
Signal (sigalrm, sigroutine );
Required ime_idx = idx;
Tick. it_value. TV _sec = 10; // The timer will be started in 10 seconds.
Tick. it_value. TV _usec = 100*1000; // 100 ms
Tick. it_interval. TV _sec = 1; // After the timer is started, the corresponding function is executed every one second.
Tick. it_interval. TV _usec = 0;
Ret = setitimer (itimer_real, & tick, null); // itimer_real
If (Ret! = 0)
{
// Debug ("timer error ");
}
This is a tradition. The sequence is to run the tick. it_value. TV _sec value first, and then run the tick. it_value. TV _usec value (note: the unit is microsecond, So multiply the millisecond value by 1000)
Then, if the value of tick. it_interval is not 0, it is called cyclically every n seconds.
When timer arrives, it will send sigalrm signal and then call the sigroutine function. This function is defined as void (fun *) (int id );
Note: Tick. it_value must have a value. If it is 0, timer is invalid.
Set the tick. it_interval value to 0 if you want to loop for only one time.
2:
Struct itimerval itimer;
// Required ime_idx = idx;
Itimer. it_interval. TV _sec = 0;
Itimer. it_interval. TV _usec = 0;
Itimer. it_value. TV _sec = 0;
Itimer. it_value. TV _usec = 0;
Setitimer (itimer_real, & itimer, null );
Sigset_t block_mask;
// Shield all unused Signals
Sigfillset (& block_mask );
Sigdelset (& block_mask, sigalrm );
Sigprocmask (sig_block, & block_mask, null );
// Sigaction
Struct sigaction sigact;
Sigfillset (& sigact. sa_mask );
Sigact. sa_handler = sigroutine;
Sigaction (sigalrm, & sigact, null );
This method is relatively advanced and looks very similar at first glance, but there are many problems with this 2 method.
For example, when you press the button or touch the screen, the program is easily closed .. I don't know why. I hope someone can give me some advice ~
So we should use the first method honestly.