简体   繁体   English

在C中实现计时器回调

[英]Implementing timer callback in c

I am new to callback functions in C. I want to create a timed callback. 我是C语言中的回调函数的新手。我想创建一个定时回调。

Scenario: I want a timer function which will trigger the callback function when timer expires. 场景:我想要一个计时器函数,它将在计时器到期时触发回调函数。 For example, every 5 sec the timer expires and calls the function. 例如,计时器每5秒过期并调用该函数。

How should I approach this problem ? 我应该如何解决这个问题?

How should you approach this problem? 您应该如何解决这个问题?

As with all problems: 与所有问题一样:

  • Figure out what you want to do precisely 弄清楚你想做什么
  • Ask yourself how you would do it yourself if you needed to (and if you could) 问问自己自己(如果需要)如何做
  • Try to formalize previous step as close as possible to single statements sentences, one step at a time. 尝试将上一步尽可能地规范化,使其尽可能接近单个语句的句子,一次只一步。
  • Identify what blocks you / what you don't know how to do. 找出阻碍您/您不知道该怎么做的因素。 Do some research on that. 做一些研究。

What you want to do precisely 您想精确地做什么

You want to "create a timed callback". 您要“创建定时回调”。 I think this means : 我认为这意味着:

  • You have a function foo doing some work 你有一个函数foo做一些工作
  • You have your program running 您正在运行程序
  • You want to be able to say "From right now, in X miliseconds, call foo " anywhere in your program 您希望能够在程序中的任何位置说“从X毫秒开始,立即调用foo

How would you do this yourself? 您自己将如何做?

I think you would, for example, launch a stopwatch with X miliseconds then keep doing whatever you were doing. 例如,我想您会在X毫秒内启动秒表,然后继续做您正在做的事情。 When the stopwatch reaches zero, you stop what you do and do the thing needed. 当秒表达到零时,您停止所做的事情并做所需的事情。 Finally, resume what you were doing. 最后,恢复您的工作。

What blocks you? 什么阻碍了你?

Judging by your question I think two things block you: 从您的问题来看,我认为有两件事会阻止您:

  • You need to understand how to do function callbacks in C. See "function pointers" 您需要了解如何在C语言中执行函数回调。请参见“函数指针”
  • You need to understand how to have a timer and do something when the timer reaches zero. 您需要了解如何使用计时器以及在计时器达到零时执行一些操作。

A few google searches will help you with both. 进行一些Google搜索会为您提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM