[Solved] Adding script to cron

Hello guys,

So i am trying to add a script to cron.daily but when i test it , it always fails. If i run the script i don’t get any error but when i try with cron it fails every time.
For reference i am using this script media cleaner.
When i run it on the command line it works as intended.
This is the permission for the files.

drwxrwxr-x 3 root dietpi   4096 Dec 21 14:18 .
drwxr-xr-x 9 root root     4096 Dec 20 18:14 ..
drwxr-xr-x 2 root root     4096 Dec 21 14:18 __pycache__
-rwxrwxrwx 1 root dietpi 166701 Oct 28 14:54 media_cleaner.py
-rw-r--r-- 1 root root     9607 Dec 21 14:18 media_cleaner_config.py

I added this to the folder /etc/cron.daily

root@tartarus:/etc/cron.daily# ls -al
total 32
drwxr-xr-x  2 root root 4096 Dec 21 14:11 .
drwxr-xr-x 85 root root 4096 Dec 18 22:26 ..
-rw-r--r--  1 root root  102 Feb 22  2021 .placeholder
-rwxr-xr-x  1 root root 1478 Jun 10  2021 apt-compat
-rwxr-xr-x  1 root root 2651 Dec 12 14:41 dietpi
-rwxr-xr-x  1 root root 1298 Jan 30  2021 dpkg
-rwxr-xr-x  1 root root  377 Feb 28  2021 logrotate
-rwxr-xr-x  1 root root   48 Dec 22 13:28 media_cleaner

Media_cleaner file:

#!/bin/bash

/opt/media_cleaner/media_cleaner.py

But when i test the cron job using the following command run-parts -v /etc/cron.daily it always fails on the media_cleaner part with the following error:

-----------------------------------------------------------
Start...
Cleaning media for server at: http://localhost:8096/emby
-----------------------------------------------------------

Traceback (most recent call last):
  File "/usr/lib/python3.9/urllib/request.py", line 1346, in do_open
    h.request(req.get_method(), req.selector, req.data, headers,
  File "/usr/lib/python3.9/http/client.py", line 1255, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/lib/python3.9/http/client.py", line 1301, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.9/http/client.py", line 1250, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.9/http/client.py", line 1010, in _send_output
    self.send(msg)
  File "/usr/lib/python3.9/http/client.py", line 950, in send
    self.connect()
  File "/usr/lib/python3.9/http/client.py", line 921, in connect
    self.sock = self._create_connection(
  File "/usr/lib/python3.9/socket.py", line 843, in create_connection
    raise err
  File "/usr/lib/python3.9/socket.py", line 831, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/media_cleaner/media_cleaner.py", line 3100, in <module>
    deleteItems=get_items(cfg.server_url, cfg.user_keys, cfg.access_token)
  File "/opt/media_cleaner/media_cleaner.py", line 1642, in get_items
    data=requestURL(url, cfg.DEBUG, 'current_user', cfg.api_request_attempts)
  File "/opt/media_cleaner/media_cleaner.py", line 797, in requestURL
    with request.urlopen(url) as response:
  File "/usr/lib/python3.9/urllib/request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.9/urllib/request.py", line 517, in open
    response = self._open(req, data)
  File "/usr/lib/python3.9/urllib/request.py", line 534, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
  File "/usr/lib/python3.9/urllib/request.py", line 494, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.9/urllib/request.py", line 1375, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "/usr/lib/python3.9/urllib/request.py", line 1349, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno 111] Connection refused>
run-parts: /etc/cron.daily/media_cleaner exited with return code 1

I am at a loss here because if i try running the script with sudo -u user its runs ok, with root it runs ok but with cron it always fails with the error connection refused.

Thank you in advance for any insight and happy holidays.

not sure what the issue of the script is but it seems it tries to connect to something, which is not working

ConnectionRefusedError: [Errno 111] Connection refused
urllib.error.URLError: <urlopen error [Errno 111] Connection refused>

Did you tried to run the script from crontab?

Another option might be to create a systemd service and use a corresponding timer. Just as an idea https://unix.stackexchange.com/questions/48203/run-script-once-a-day-with-systemd

Joulinar
Hello i did try to add it to crontab using the command crontab -u root -e and added the following line.

5 * * * * /usr/bin/python3 /opt/media_cleaner/media_cleaner.py >> /var/log/media_cleaner/log

After the 5 minutes nothing happened. Again running the command in the terminal works as intended.

you could have a look if there is anything visible on journalctl

journalctl -u cron

Hello Joulinar

I checked the journal but nothing was being passed.
I kind of give up on crontab so i decided to create a systemd unit on a timer, as you suggested

Created the service

nano /etc/systemd/system/media-cleaner.service



[Unit]
Description=media cleaner service 
Wants=network-online.target 
After=network-online.target

[Service] 
Type=simple 
User=root 
Group=dietpi 
WorkingDirectory=/opt/media_cleaner/ 
ExecStart=/usr/bin/python3 /opt/media_cleaner/media_cleaner.py 
SyslogIdentifier=media-cleaner

[Install] 
WantedBy=multi-user.target

Enable it with

systemctl enable media-cleaner.service

Run the service

systemctl start media-cleaner.service

checked the log

journalctl -u media-cleaner.service

all OK

Created a timer

nano /etc/systemd/system/media-cleaner.timer



[Timer] 
OnCalendar=daily 
Unit=media-cleaner.service

Did some more checks:

systemd-analyze verify /etc/systemd/system/media-cleaner.service



systemd-analyze verify /etc/systemd/system/media-cleaner.timer

Start the timer:

systemctl start media-cleaner.timer

And finally check the timer list:

systemctl list-timers -all

NEXT                        LEFT        LAST                        PASSED       UNIT                         ACTIVATES
Sat 2021-12-25 00:00:00 GMT 9h left     n/a                         n/a          media-cleaner.timer          media-cleaner.service

And to triple check:

systemctl status media-cleaner.*
● media-cleaner.timer
     Loaded: loaded (/etc/systemd/system/media-cleaner.timer; static)
     Active: active (waiting) since Fri 2021-12-24 14:28:05 GMT; 48min ago
    Trigger: Sat 2021-12-25 00:00:00 GMT; 8h left
   Triggers: ● media-cleaner.service

Dec 24 14:28:05 tartarus systemd[1]: Started media-cleaner.timer.



systemctl status media-cleaner.service
● media-cleaner.service - Media Cleaner Service
     Loaded: loaded (/etc/systemd/system/media-cleaner.service; disabled; vendor preset: enabled)
     Active: inactive (dead) since Fri 2021-12-24 15:10:12 GMT; 6min ago
TriggeredBy: ● media-cleaner.timer
    Process: 578264 ExecStart=/usr/bin/python3 /opt/media_cleaner/media_cleaner.py (code=exited, status=0/SUCCESS)
   Main PID: 578264 (code=exited, status=0/SUCCESS)
        CPU: 368ms

Dec 24 15:10:12 tartarus Media-Cleaner[578264]: -----------------------------------------------------------
Dec 24 15:10:12 tartarus Media-Cleaner[578264]: Summary Of Deleted Media:
Dec 24 15:10:12 tartarus Media-Cleaner[578264]: * Items Deleted = 0    *
Dec 24 15:10:12 tartarus Media-Cleaner[578264]: -----------------------------------------------------------
Dec 24 15:10:12 tartarus Media-Cleaner[578264]: [NO ITEMS TO DELETE]
Dec 24 15:10:12 tartarus Media-Cleaner[578264]: -----------------------------------------------------------
Dec 24 15:10:12 tartarus Media-Cleaner[578264]: -----------------------------------------------------------
Dec 24 15:10:12 tartarus Media-Cleaner[578264]: Done.
Dec 24 15:10:12 tartarus Media-Cleaner[578264]: -----------------------------------------------------------
Dec 24 15:10:12 tartarus systemd[1]: media-cleaner.service: Succeeded.

edit: Happy holidays for all

thx for sharing your final solution. Good it is working for you.