Search code examples
linuxcronraspberry-pi

Is there a way to make crontab run a gnu screen session?


I have a discord bot running on a raspberry pi that i need to restart every day, I'm trying to do this through crontab but with no luck.

It manages to kill the active screen processes but never starts an instance, not that I can see with "screen -ls" and I can tell that it doesn't create one that I can't see as the bot itself does not come online.

Here is the script:

#!/bin/bash
sudo pkill screen
sleep 2
screen -dmS discordBot
sleep 2
screen -S "discordBot" -X stuff "node discordBot/NEWNEWNEWN\n"

Here is also the crontab:

0 0 * * * /bin/bash /home/admin/discordBot/script.sh

Is it possible to have crontab run a screen session? And if so how?

Previously I tried putting the screen command stright into cron but now I have it in a bash script instead. If I run the script in the terminal it works perfectly, it’s just cron where it fails. Also replacing "screen" with the full path "/usr/bin/screen" does not change anything.


Solution

  • So the best way of doing it, without investigating the underlying problem would be to create a systemd service and putting a restart command into cron.

     

    /etc/systemd/system/mydiscordbot.service:

    [Unit]
    Description=A very simple discord bot
    
    [Service]
    Type=simple
    ExecStart=node /path/to/my/discordBot.js
    
    [Install]
    WantedBy=multi-user.target
    

    Now you can run your bot with systemctl start mydiscordbot and can view your logs with journalctl --follow -u mydiscord bot

    Now you only need to put

    45 2 * * * systemctl restart discordbot 
    

    into root's crontab and you should be good to go.

    You probably should also write the logs into a logfile, maybe /var/log/mydiscordbot.log, but how and if you do that is up to you.


    OLD/WRONG ANSWER:

    cron is run with a minimal environment, and depending on your os, /usr/bin/ is probably not in the $PATH var. screen is mostlikely located at /usr/bin/screen, so cron can't run it because it can't find the screen binary. try replacing screen in your script with /usr/bin/screen

    But the other question here is: Why does your discord bot need to be restarted every day. I run multiple bots with 100k+ users, and they don't need to be restarted at all. Maybe you should open a new question with the error and some code snippets.