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

相关推荐
未济2 天前
linux 配置环境变量
linux
傲世仙尊2 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
_艾伦 耶格尔.2 天前
进程间通信
linux
AI职业加油站2 天前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
Liuqy-052 天前
Linux IO编程——静态库、动态库
linux
此冬歌咏2 天前
K8s 节点故障实战:优雅驱逐 31 秒,硬故障 331 秒,以及那个永远 Pending 的 Pod
运维·k8s
彧azz2 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
-梅2 天前
linux(8) 软硬链接
linux·运维·服务器
Wang's Blog2 天前
Java 项目实战: 外卖平台-文件下载与ServletOutputStream回写浏览器
服务器·项目开发