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` 函数,它将在每天的指定时间执行命令。

相关推荐
轻松Ai享生活3 小时前
5 节课深入学习Linux Cgroups
linux
christine-rr4 小时前
linux常用命令(4)——压缩命令
linux·服务器·redis
三坛海会大神5554 小时前
LVS与Keepalived详解(二)LVS负载均衡实现实操
linux·负载均衡·lvs
東雪蓮☆4 小时前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs
qq_264220894 小时前
LVS负载均衡群集和LVS+Keepalived群集
运维·负载均衡·lvs
乌萨奇也要立志学C++5 小时前
【Linux】进程概念(二):进程查看与 fork 初探
linux·运维·服务器
雨落Liy5 小时前
Nginx 从入门到进阶:反向代理、负载均衡与高性能实战指南
运维·nginx·负载均衡
Yyyy4825 小时前
Nginx负载均衡集群实验步骤
运维·nginx·负载均衡
绿箭柠檬茶6 小时前
Ubuntu 服务器配置转发网络访问
服务器·网络·ubuntu
獭.獭.6 小时前
Linux -- 信号【上】
linux·运维·服务器