go 每天定时任务 --chatGPT

问:clearLog(hour,cmds),定时执行shell 命令,hour 为每天的几点,cmds 为linux命令数组字符串(如 1,{"ls","cd"})

gpt:

要编写一个 Go 函数 `clearLog`,该函数可以定时执行 shell 命令,并且接受每天的几点和命令数组字符串作为参数,你可以使用 Go 的 `time` 包来实现定时执行以及 `exec` 包来执行 shell 命令。下面是一个示例:

```go

package main

import (

"fmt"

"os"

"os/exec"

"strings"

"time"

)

func clearLog(hour int, cmdsStr string) {

cmds := strings.Split(cmdsStr, ",")

if len(cmds) == 0 {

fmt.Println("命令数组不能为空")

return

}

// 计算下一次执行的时间

now := time.Now()

nextRun := time.Date(now.Year(), now.Month(), now.Day(), hour, 0, 0, 0, now.Location())

if now.After(nextRun) {

nextRun = nextRun.Add(24 * time.Hour)

}

ticker := time.NewTicker(nextRun.Sub(now))

for {

select {

case <-ticker.C:

for _, cmd := range cmds {

cmd = strings.TrimSpace(cmd)

if cmd != "" {

fmt.Printf("执行命令: %s\n", cmd)

err := executeShellCommand(cmd)

if err != nil {

fmt.Printf("执行命令出错: %v\n", err)

}

}

}

// 重新计算下一次执行的时间

nextRun = nextRun.Add(24 * time.Hour)

ticker.Reset(nextRun.Sub(time.Now()))

}

}

}

func executeShellCommand(command string) error {

cmd := exec.Command("bash", "-c", command)

cmd.Stdout = os.Stdout

cmd.Stderr = os.Stderr

return cmd.Run()

}

func main() {

hour := 1 // 每天的几点执行,范围 0 到 23

cmds := "ls, cd /path/to/directory" // 命令数组字符串,用逗号分隔

clearLog(hour, cmds)

}

```

在这个示例中,我们首先计算了下一次执行的时间,确保它是将来的时间。然后使用 `time.NewTicker` 创建一个定时器,以在下一次执行的时间触发。在每次触发时,我们执行提供的命令数组中的每个命令。执行命令的函数 `executeShellCommand` 使用 Go 的 `os/exec` 包来运行 shell 命令。

请替换 `hour` 和 `cmds` 变量的值为你的实际需求,以及命令数组字符串中的命令列表。然后,在 `main` 函数中调用 `clearLog` 函数,它将在每天的指定时间执行命令。

相关推荐
402 Payment Required5 分钟前
serv00 ssh登录保活脚本-邮件通知版
运维·chrome·ssh
小柏ぁ10 分钟前
calico/node is not ready: BIRD is not ready: BGP not established with xxx
运维·docker·kubernetes
Mintimate31 分钟前
云服务器 Linux 手动 DD 安装第三方 Linux 发行版:原理与实战
linux·运维·服务器
RussellFans42 分钟前
Linux 环境配置
linux·运维·服务器
网硕互联的小客服1 小时前
503 Service Unavailable:服务器暂时无法处理请求,可能是超载或维护中如何处理?
服务器·git·github
高冷的肌肉码喽1 小时前
Linux-进程间的通信
linux·运维·服务器
乖乖是干饭王2 小时前
Linux系统编程中的_GNU_SOURCE宏
linux·运维·c语言·学习·gnu
jekc8682 小时前
禅道18.2集成LDAP
linux·运维·服务器
weixin_434936282 小时前
k8S 命令
linux·容器·kubernetes
weixin_307779132 小时前
Linux下GCC和C++实现统计Clickhouse数据仓库指定表中各字段的空值、空字符串或零值比例
linux·运维·c++·数据仓库·clickhouse