Lengthy sleep command not working in script


Question

I've written a su.d script to periodically (every 4 hours) back up data from an app using a looped sleep command:



#!/system/bin/sh

(
# Wait for boot to complete
until [ "$(getprop sys.boot_completed)" ]
do
sleep 300
done

while true
do
(
new_dir="/storage/emulated/0/temp/AppData/$(date '+%Y%m%d-%H%M')"
mkdir -p $new_dir
cp /data/data/com.example.app/files/*.json $new_dir

echo "$(date '+%F %T') | app data backup OK!" >> /storage/emulated/0/su.d.log
) &

sleep 14400 # 4 hours
done
) &


In practice, the script backs up the data only after boot—not every 4 hours.



However, if I enter a remote shell via adb and leave it alone, then the data does get backed up every 4 hours.



How can I force the periodic backup without being permanently connected to a PC? (And why isn't it working as expected?)






EDITS




  1. @Irfan Latif's comment gave me the idea of trying a different interpreter (busybox ash - #!/system/xbin/sh), but the result was the same. I'll try @mirabilos's daemonise suggestion (sh -T- -c '...') next.


  2. Tried @mirabilos's daemonise suggestion with the same result: backs up data only after boot.


  3. Tried nohup:



    nohup /system/bin/sh -T- -c '...' >/dev/null 2>&1 &


    Same result.



Answer

Having no success with sleep, I ended up going the crond route, as suggested by @Irfan Latif:




  • /system/su.d/99crond (-rwx------ root root)



    #!/system/bin/sh

    # File: 99crond
    # Desc: Start cron daemon

    (
    # Wait for boot to complete
    until [ "$(getprop sys.boot_completed)" ]
    do
    sleep 2
    done

    # Symlink default cron dir to /data/local/crontabs
    mount -o remount,rw /
    mkdir -p /var/spool/cron
    ln -s /data/local/crontabs /var/spool/cron/crontabs
    mount -o remount,ro /

    crond -b

    echo "$(date '+%F %T') | su.d/99crond OK!" >> /storage/emulated/0/su.d.log
    ) &

  • /data/local/crontabs/root (-rw------- root root)



    # /data/local/crontabs/root: Android root user crontab

    SHELL=/system/bin/sh
    PATH=/sbin:/system/bin:/system/xbin:/data/local/bin

    #.--------------------------- Minute (M) (0--59)
    #| .---------------------- Hour (H) (0--23, 0 = midnight)
    #| | .---------------- Day of Month (DoM) (1--31)
    #| | | .---------- Month (MON) (1--12) OR jan,feb,mar, ...
    #| | | | .---- Day of Week (DoW) (0--6, Sunday = 0 or 7) OR sun,mon,tue, ...
    #| | | | |
    #M H DoM MON DoW COMMAND
    0 */4 * * * /data/local/bin/cron_backup.sh
    #


    FURTHER READING




  • /data/local/bin/cron_backup.sh (-rwxr-xr-x root shell)



    #!/system/bin/sh

    # File: cron_backup.sh
    # Desc: Back up app data (periodically with crond)

    new_dir="/storage/emulated/0/temp/AppData/$(date '+%Y%m%d-%H%M')"
    mkdir -p "$new_dir"
    cp /data/data/com.example.app/files/*.json "$new_dir"

    echo "$(date '+%F %T') | cron_backup.sh OK!" >> /storage/emulated/0/crond.log






As pointed out by @Ramast here, these three files alone were not quite sufficient to get crond working: /system/etc/passwd is also required for user root to be recognised, so...



mount -o remount,rw /system
echo "root:x:0:0:root:/data:/system/bin/sh" >> /system/etc/passwd
chmod 644 /system/etc/passwd
mount -o remount,ro /system


After all that is done the data gets backed up periodically as desired.


Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes