定时器相关API(SDL_timer.h):
1. Uint32 SDL_GetTicks():
获取从SDL库初始化(定时器模块初始化)开始到当前的运行时间(ms);
2. Uint64 SDL_GetPerformanceCounter():
获取高精度定时器的当前值;
3. Uint64 SDL_GetPerformanceFrequency():
获取高进度定时器频率(每秒钟高精度定时器的次数);
4. void SDL_Delay(Uint32 ms):
延迟函数;
5. SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *param):
向系统请求增加一个定时器.
SDL_TimerID: 定时器的ID,若该值为NULL,表示请求失败;
interval:
定时间隔;
callback:
回调函数,定时时间到后会调用此函数;
备注: typedef Uint32 (* SDL_TimerCallback)(Uint32 interval, void *param):
该函数返回值为下次唤醒的时长,若返回0,则不会再唤醒.
6. SDL_bool SDL_RemoveTimer(SDL_TimerID id): 删除给定id的定时器,返回值表示是否删除成功.
7.int SDL_SetTimer(Uint32 interval, SDL_TimerCallback callback);此函数也是启动定时器和删除定时器的版本,但是已经被上面两个API替代。
参考程序示例一:
#include <stdio.h>
#include <SDL/SDL.h>
int i = 0;
//回调函数
Uint32 my_fun(Uint32 interval, void *param)
{
printf("interval: %d *param: %d\n", interval, *(int*)param);
i++;
return interval;
}
int main(void)
{
int ret;
Uint32 time;
//定时器ID
SDL_TimerID timeId = NULL;
//SDL初始化
ret = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
if (-1 == ret)
{
printf("SDL_Init failed..\n");
goto err0;
}
//延时函数 单位是毫秒
//SDL_Delay(1000);
//返回从SDL初始化开始到现在的时间 单位是毫秒
time = SDL_GetTicks();
printf("%u\n", time);
//添加定时器
timeId = SDL_AddTimer(100, my_fun, &time);
if (NULL == timeId)
{
printf("AddTime failed...\n");
goto err0;
}
while(1)
{
if (10 == i)
break;
}
//删除定时器
SDL_RemoveTimer(timeId);
//关闭SDL
SDL_Quit();
return 0;
err0:
return -1;
}
运行结果如下:
原来版本定时器示例二:
#include <stdio.h>
#include <SDL/SDL.h>
int i = 0;
//定时器的第二种方法 此API已经被SDL_AddTimer SDL_RemoveTimer取代
Uint32 fun(Uint32 interval)
{
printf("interval: %d\n", interval);
i++;
return interval;
}
int main(void)
{
int ret;
Uint32 time;
//定时器ID
SDL_TimerID timeId = NULL;
//SDL初始化
ret = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
if (-1 == ret)
{
printf("SDL_Init failed..\n");
goto err0;
}
//延时函数 单位是毫秒
//SDL_Delay(1000);
//返回从SDL初始化开始到现在的时间 单位是毫秒
time = SDL_GetTicks();
printf("%u\n", time);
SDL_SetTimer(100, fun);
while(1)
{
if (10 == i)
break;
}
//删除定时器
SDL_SetTimer(0, NULL);
//关闭SDL
SDL_Quit();
return 0;
err0:
return -1;
}
程序运行结果如下: