Write a script to run once a day, but not if rclone is already running

Newbie warning.

I have rclone set up on my Unraid-server, and set it to run the backup/copy script once per day.

If the script is not finished before the next time it is supposed to start it will start a second instance of backup, thus ruining my network speed.

I've asked in the Unraid-forum, and the tip I got was this:

I prefer to use the status file method e.g.

  1. Check if a status file exists. If yes, exit script.
  2. If files does not exist then touch status file (to create it) and then do stuff and once all done delete status file

I've tried some googling and searched on this forum, but I'm not sure how to proceed.

Something like: https://github.com/animosity22/homescripts/blob/master/scripts/upload_cloud

Thanks!

So if I use this script it would work?

if [[ "pidof -x $(basename $0) -o %PPID" ]]; then exit; fi
rclone copy /mnt/user/Media gcrypt:allmedia --bwlimit 8M --transfers 2 -v

Edit, it might be better in this order.

This is what I use for my borg + rclone backup script on Unraid

# Close if rclone running
if pidof -x rclone >/dev/null; then
    echo "$(date "+%m-%d-%Y %T") : RClone already running, exiting" >> $LOGFILE 2>&1
    exit
    exit
fi

Bash (Linux) solution - put this at the top of your script to make sure that only one instance can ever run at one time:

#!/bin/bash

#Lock the file so only one of these scripts can run at once.
lockfile -r 0 /tmp/uploadscript.lock || exit 1

In batch (windows) you can use this to basically the same strategy (except it locks on the scriptfile itself rather than an external file):

@echo off

::Before we start, get a file-lock on this script to prevent concurrent instances
call :getLock
exit /b

:getLock
:: The CALL will fail if another process already has a write lock on the script
call :main 9>>"%~f0"
exit /b
:: At this point the file is locked and only one process can act here at once - go to MAIN to start the script

:main

In either case you obviously need to put whatever commands you want below this - and if you want it to run once a day for example then you need a scheduler to run it at those times.

In Wnidows you can use task-scheduler or NSSM
In Linux you would typically use cron to do the same

Due to the file-lock, if the scheduler tries to run the script again before the first script was done - it will simply fail with an error-code in the log. Therefore it is safe to set it to run aggressively if you want as the OS ensures multiple instances can not run simultaneously.

2 Likes

If you want a really simple cross platform way of doing this (works on Windows, macOS, Linux), then just add --rc to your command. This will fail if there is an rc server already running.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.