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
    }

    ticker := time.NewTicker(time.Duration(hour) * time.Hour)

    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)
                    }
                }
            }
        }
    }
}

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 // 时间间隔,单位:小时
    cmds := "ls, cd /path/to/directory" // 命令数组字符串,用逗号分隔

    clearLog(hour, cmds)
}
```

在这个示例中,我们定义了一个 `clearLog` 函数,它接受小时间隔和命令数组字符串作为参数。使用 `time.NewTicker` 来创建一个定时器,每隔指定的小时间隔触发一次。在定时器触发时,我们执行提供的命令数组中的每个命令。执行命令的函数 `executeShellCommand` 使用 Go 的 `os/exec` 包来运行 shell 命令。

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

你可能感兴趣的:(golang,chatgpt)