将上面添加添加到gin框架中,可以使用web端进行控制开启与启动
时间: 2024-02-27 12:52:57 浏览: 30
好的,请参考以下代码:
```go
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// 状态变量,用于判断定时器是否开启
isRunning := false
// 定时器函数
funcTicker := func() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
fmt.Println("定时器触发")
}
}
}
// 控制定时器开启与停止的路由
router.GET("/timer/:action", func(c *gin.Context) {
action := c.Param("action")
if action == "start" {
// 如果定时器已经在运行,则返回错误提示
if isRunning {
c.JSON(http.StatusBadRequest, gin.H{"error": "Timer is already running"})
return
}
// 否则,开启定时器,并将状态变量置为 true
go funcTicker()
isRunning = true
c.JSON(http.StatusOK, gin.H{"message": "Timer started"})
} else if action == "stop" {
// 如果定时器已经停止,则返回错误提示
if !isRunning {
c.JSON(http.StatusBadRequest, gin.H{"error": "Timer is not running"})
return
}
// 否则,将状态变量置为 false
isRunning = false
c.JSON(http.StatusOK, gin.H{"message": "Timer stopped"})
} else {
// 如果 action 参数既不是 start 也不是 stop,则返回错误提示
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid action"})
}
})
// 运行 HTTP 服务器
router.Run(":8080")
}
```
以上代码使用了 Gin 框架来实现 HTTP 服务器,通过访问 `/timer/start` 和 `/timer/stop` 路由来控制定时器的开启和停止。在定时器函数 `funcTicker()` 中,可以根据需求修改定时器的触发间隔和触发的代码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)