VSOA Timer

更新时间:
2023-12-21
下载文档

VSOA Timer

VSOA Timer 为 C 语言环境下的微服务开发提供了便捷的定时器功能,本节将指导您如何使用 VSOA Timer。

开发须知

使用 VSOA Timer 时,应使用 vsoa_timer_init 接口初始化定时器服务。 定时器服务初始化后,VSOA 将创建一个定时器服务线程用于处理所有定时器回调事件,因此定时器所处理的事件应尽量简单,否则会阻塞后续定时器回调函数的执行。VSOA 定时器提供的接口是线程安全的。

开发步骤

  1. 调用 vsoa_timer_init 接口,初始化定时模块。
  2. 调用 vsoa_timer_create 接口,创建一个定时器实例,此时会返回一个 vsoa_timer_t 类型的指针。
  3. 调用 vsoa_timer_startvsoa_timer_start_ms 接口,初始化并启动定时器。其中vsoa_timer_start 的时间单位为 ns,vsoa_timer_start_ms 的时间单位为 ms。
  4. 当不再需要该定时器时,可调用 vsoa_timer_stop 接口停止该定时器。

说明:
VSOA Timer 接口说明可参考 C 扩展编程手册

代码示例

#ifdef SYLIXOS
#include <sys/vproc.h>
#endif
#include <stdio.h>
#include "vsoa_timer.h"
#include "vsoa_platform.h"

/* Timer ontime count */
static int t1_cnt = 0;
static int t2_cnt = 0;

/*
 * Timer 1 callback
 */
static void t1_callback (void *arg, vsoa_timer_t *t)
{
    int *cnt = (int *)arg;

    printf("TIMER 1 ontime! count: %d\n", *cnt);

    (*cnt)++;
}

/*
 * Timer 2 callback
 */
static void t2_callback (void *arg, vsoa_timer_t *t)
{
    int *cnt = (int *)arg;

    printf("TIMER 2 ontime! count: %d\n", *cnt);

    (*cnt)++;
}

/*
 * main function
 */
int main (int argc, char **argv)
{
    vsoa_timer_t  *t1, *t2;

#ifdef SYLIXOS
    vprocExitModeSet(getpid(), LW_VPROC_EXIT_FORCE);
#endif

    printf("Timer demo start!\n");

    /*
     * Must be initialized before using any timer API
     */
    vsoa_timer_init();

    /*
     * Create two timers
     */
    t1 = vsoa_timer_create();
    t2 = vsoa_timer_create();

    /*
     * Start the timer with different first expiration time and periodic timing time
     * When `interval` is 0, it means one-shot timer.
     * The callback will executed in the timer service thread context.
     */
    vsoa_timer_start_ms(t1, 1000, 1000, t1_callback, &t1_cnt);
    vsoa_timer_start_ms(t2, 2000, 2000, t2_callback, &t2_cnt);

    vsoa_thread_msleep(10000);

    /*
     * Delete the timer, this function can also be called when the timer is running
     */
    vsoa_timer_delete(t1);
    vsoa_timer_delete(t2);

    printf("All Timer deleted!\n");

    /*
     * The timer has been removed and nothing has been printed for this time
     */
    vsoa_thread_msleep(5000);

    printf("Exit!\n");

    return  (0);
}

注意事项

C/C++ 定时器服务程序编译时需链接如下表所示的 VSOA 动态库,在 RealEvo-IDE 中配置时请参考 C/C++ 开发示例,Linux 下开发请参考 搭建 Linux 运行环境 提供的 C 语言范例进行配置。

库名称功能
libvsoa-server.so提供服务端功能
文档内容是否对您有所帮助?
有帮助
没帮助