0

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.

hoa.le
  • 13
  • 4
  • Probably go binary isn't in your `PATH`. You can check error messages in cronjob by being logged on the machine while the cronjob is active. you will get a notification of a new e-mail message after the cronjob runs, it will have the error. – Niloct Aug 14 '22 at 05:00
  • @Niloct Thanks for your sharing, the strange thing is I run my piece of code complete normal manually but in cron job, it can be executed. There is no error in cronjob log. https://i.imgur.com/ps4Ji76.png – hoa.le Aug 14 '22 at 05:33
  • 3
    Do not use go run for such stuff. – Volker Aug 14 '22 at 06:37
  • 1
    "the strange thing is" - see [this question](https://stackoverflow.com/q/2388087/11810946) for an explanation. – Brits Aug 14 '22 at 09:37

1 Answers1

1

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

Umut Gerçek
  • 630
  • 6
  • 9
  • Thanks sir, that helped a lot. I fixed my problem by adding go binary path at the begin of crontab file. – hoa.le Aug 16 '22 at 06:23