无法使用 cron 作业运行一个使用 os 库的 Go 应用程序。

huangapple go评论68阅读模式
英文:

Can not running a Go app (using os library) with cron job

问题

我在尝试使用cron作业运行Go应用程序时遇到了问题。似乎os库的每个函数都无法在cron作业中执行。以下是我的代码。我已经搜索了很长时间,但还没有找到任何解决方案。

这是我的代码。

package main

import (
	"fmt"
	"os"
	"os/exec"
)

func main() {
	out, err := exec.Command("ls").Output()
	file, _ := os.Create("test.txt")
	_, err1 := file.Write([]byte(string(out) + "\n"))
	if err == nil && err1 == nil {
		fmt.Println("test")
	}
	fmt.Println(string(out))
}

这是我的cron作业

* * * * * go run /root/code/main.go

请帮我解决这个问题,或者提供任何在cron作业中运行Go应用程序的建议。

英文:

I had a problem when I tried run a Go app with cron job. It's seem that every func of os library can not execute in cron job. Here is my code. I've searched for a lot of time but haven't got any solotion yet.

Here is my code.

package main

import (
   "fmt"
   "os"
   "os/exec"
)

func main() {
   out, err := exec.Command("ls").Output()
   file, _ := os.Create("test.txt")
   _, err1 := file.Write([]byte(string(out) + "\n"))
   if err == nil && err1 == nil {
	   fmt.Println("test")
   }
   fmt.Println(string(out))
}

Here is my cron job

* * * * * go run /root/code/main.go

Please help me fix this problem or any recommend to run a go app with cron job.

答案1

得分: 1

默认情况下,cron作业是使用root用户运行的,可能在root用户的路径中没有go二进制文件。
要检查这一点,您可以运行以下命令:

# crontab -e
* * * * * whoami >> /tmp/debug.txt && where go && echo OK >> /tmp/debug.txt || echo ERROR >> /tmp/debug.txt

这将显示用户信息和“是否可以找到go二进制文件”的信息。

您可以更改运行cron作业的用户。运行cron作业的用户

更好的方法

正如其他人所说,使用go run运行Go代码不是一个好主意。每次编译器都需要编译代码并运行它。

如果您运行go build并运行生成的可执行文件,它将简化您的工作流程。此外,默认情况下,go二进制文件是包含所有依赖项的单个二进制文件,这简化了很多事情。您只需在任何位置运行./executable-name即可。

英文:

By default, cron jobs are run with the root user, and probably there is no go binary in your root user's path.
To check this, you can run.

# crontab -e
* * * * * whoami >> /tmp/debug.txt && where go && echo OK >> /tmp/debug.txt || echo ERROR >> /tmp/debug.txt

Which will show you user info and "Can I find go binary" information.

You can change the user who runs the cronjob

Better Way

As others said, it's not a good idea to run Go code with go run. Each time compiler needs to compile the code and run it.

If you run go build and run the produced executable, it'll simplify your workflow. Also, by default, go binaries are single binaries that contain all dependencies, which simplifies lots of things. You can just ./executable-name anywhere

huangapple
  • 本文由 发表于 2022年8月14日 12:51:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/73349193.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定