0

I want to define a cronjob like this:

@hourly /path/to/my/script.sh &> "/path/to/my/logs/$(date +%Y-%m-%d_%H-%M-%S.txt)"

So it should write the output of the script to a log file. Now I want to make a second script (preferably with PHP) that reads all files in /path/to/my/logs/ and sends the files via mail. It shouldn't be a problem to create such a script, but I wonder how I can detect if the cronjob that created a file is done and no longer writing to the file. I don't want to send a file that was created but the cronjob still writes to.

Is there a general way to detect that and also a way in PHP to detect that?

Nono
  • 111

2 Answers2

1

You may want to use a handy little tool like the Crontab Generator to build the job definition. To run a job hourly, you can do something like this:

0 * * * * /path/to/script.sh > /path/to/output/log_$(date +\%Y-\%m-\%d).txt >/dev/null 2>&1

From there, you can have your PHP script use the filemtime function to get the last time the file was modified. If the cron job takes X seconds to run and the output file has a modification date under X+60 seconds (or any number you're comfortable with), then you can have the script read the data and process it however you wish.

  • I have also thought about this, but the runtime of the script is variable and can last from a few seconds to several minutes. But if there is no better solution, I will give this a try. – Nono Mar 04 '21 at 17:32
0

Jobs run through cron, crontab, aren't run in the same runtime environment that you have on your desktop. None of your PATH changes, or other environment variable settings are automatically propagated to your cron job. For example, there's no $DISPLAY, so GUI programs need special treatment (read man xhost).

One can set environment variables for all one's cron jobs in the crontab file Read man 5 crontab.

Look at the results of echo "=== set ===";set;echo "=== env ===";env | sort;echo "=== alias ===";alias in each of your environments.

Since the command part of the crontab line is, by default, interpreted by /bin/sh, which has a simpler syntax than /bin/bash, I recommend having command be a call to a bash script (executable, mounted, starts with #!/bin/bash) which sets up the environment, then calls the desired program.

waltinator
  • 36,399