[SCRIPT][UPDATED 03.26.14] Fix Lag, Defrag/Free Memory with |=>TrimDropOff<=|

Search This thread

defiant07

Senior Member
Feb 26, 2013
410
496
Updated 03.26.14 - Released v2.1 - bug fixes and code cleaned

Introduction:
I am by no means a developer. I am just an android enthusiast who has learned a bit of bash. The reason I made this script was that settings>>wifi>>advanced was not promptly turning wifi off when my device would sleep; sometimes it would not turn off at all. So I figured since I am making a script to resolve this issue I might as well add a couple of other functions as well. To this end I noticed some people saying THIS APP was helpful and I missed the Flush-O-Matic script from V6 SuperCharger so I added fstrim and drop_caches=3 to the script.

What will this do?
  • The script will allow you to sync wifi, fstrim, and/or drop_caches=3 with sleep and/or it will allow you to schedule fstrim and/or drop_caches=3 using crond. The scheduling option can work on either a hourly (you can choose to run desired programs every hour on the hour, every two hours on the hour, every 3 hours on the hour, etc) or daily basis (you can choose to run desired programs at a given time on the hour).
  • Both the sync and schedule options will load themselves in to memory each boot and each time your device goes to sleep and/or when scheduled the scripts will depending on your options: (1) sync your data so as to ensure no data is lost; (2) TRIM your /system, /data, and /cache partitions; (3) DROP CACHES = 3; and (4) turn off wifi.
  • In addition, there is also an on-the-fly script to manually trim partitions and drop caches when desired.

Benefits:
  • Reduce lag/improve i/o efficiency (see THIS and THIS).
  • Although android automatically invokes fstrim when certain conditions are met, these criteria could seldom if ever be met depending upon your usage style. The init.d script should ensure fstrim is invoked more frequently for most users.
  • Should use less ram than apps that perform similar functions (I say should because I have never used such apps, but I imagine they consume more that .2-.5 mb of ram).

Requirements:

Warning/Disclaimer:
Although these scripts function as intended on my device – Nexus 7 (2013), SlimKat (weekly), ElementalX...Use at your own risk. Neither I nor XDA are responsible for any possible deleterious effects.

Known Issues/Bugs:
  • If you use the sync option, scripts with a lower priority than Z99 will not execute.
  • The log files don't always display as intended...dunno why...any help/suggestions would be appreciated.
  • Let me know if you find any others :p.

Install, Usage/Verification, & Uninstall:
Install -
  1. Note: If you use crond for other tasks, both the install and uninstall routine account for this potential contigency and should leave your other crond tasks uneffects.
  2. make a nandroid backup
  3. download the zip (<<NOT flashable) attached to this post
  4. extract the zip’s contents
  5. if you were/are using the first version of this script manually delete: /etc/init.d/07TrimDropOff, /data/TrimDropOff_Awake.log, and /data/TrimDropOff_Sleep.log
  6. run TrimDropOffInstaller with superuser permission via terminal or script manager.
  7. follow the scripts prompts
  8. reboot
  9. enjoy

Usage/Verification -
  • Assuming you have followed the install procedure, next, put your device to sleep and then wake it if you are using the sync option.
  • Now check the various logs in /data/TrimDropOff. The logs will show the time, the script’s PIDs, the path of the PIDs (just to double-check the PIDs are correct), the ram used by the PIDs, action(s) preformed (amount trimmed from each partition and/or if drop_cahes was run), or errors.
  • If you want verify manually via terminal do [pgrep -f TrimDrop] for the sync option or [pgrep crond] for the scheduling option to get the PIDs, do [cat /proc/PID/cmdline] for each PID to verify it truly belongs to Z99TrimDropOff or crond, and do [dumpsys meminfo | grep PID] for each PID to verify ram usage (this command will yield duplicates, which can be disregarded and may output undesired additional results, which can be filtered by looking through the results for the relevant PID).
  • To use the on-the-fly script to trim and/or drop as desired, in terminal do [su -c trimdrop].
  • Should you want to reconfigure your setup, uninstall before reinstalling to avoid potential issues.

Uninstall -
  • Note: If you use crond for other tasks, both the install and uninstall routine account for this potential contigency and should leave your other crond tasks uneffects.
  • Rerun TrimDropOffInstaller with superuser permission and use uninstall option at the beginning of the script.
  • Reboot and all will be back to as it was before.

To-Do List:
  • Make in to an AROMA package.
  • I don't know, you tell me :).

Code:
#!/system/bin/sh

# This script was authored by Defiant07 @ xda. Feel free to use it as you see fit, but please give proper credits.
# Big thanks to zeppelinrox, dk_zero-cool, & gu5t3r @ xda for their contributions to portions of this script (see the code of my other script SwapItOn @ xda for detailed citations).
# Read Karl Marx.

input_error(){
echo "That is not a valid input...try again...bye :p."
exit 69
}

mount_rw(){
mount -o remount,rw / 2>/dev/null
mount -o remount,rw rootfs 2>/dev/null
busybox mount -o remount,rw / 2>/dev/null
busybox mount -o remount,rw rootfs 2>/dev/null
mount -o remount,rw /system 2>/dev/null
busybox mount -o remount,rw /system 2>/dev/null
busybox mount -o remount,rw $(busybox mount | awk '/system /{print $1,$3}') 2>/dev/null
}

mount_ro(){
mount -o remount,ro / 2>/dev/null
mount -o remount,ro rootfs 2>/dev/null
busybox mount -o remount,ro / 2>/dev/null
busybox mount -o remount,ro rootfs 2>/dev/null
mount -o remount,ro /system 2>/dev/null
busybox mount -o remount,ro /system 2>/dev/null
busybox mount -o remount,ro $(busybox mount | awk '/system /{print $1,$3}') 2>/dev/null
}

clear
if [ ! "`busybox`" ]; then
echo "Missing busybox...try again...bye :p."
exit 69
fi
id=$(id); id=${id#*=}; id=${id%%[\( ]*}
if [ "$id" = "0" ] || [ "$id" = "root" ]; then
echo "" 1>/dev/null
else
echo "Not running as root...try again...bye :p."
exit 69
fi
if [ ! -d /etc/init.d ]; then
echo "Missing /etc/init.d...try again...bye :p."
exit 69
fi
if [ ! "`grep -r fstrim /system/bin`" ] && [ ! "`grep -r fstrim /system/xbin`" ]; then
echo "Missing fstrim...try again...bye :p."
exit 69
fi
echo "Do you want to install or uninstall TrimDropOff?"
echo "Note: If you are rerunning this script to"
echo "reconfigure your setup, uninstall first."
echo -n "Input (i)nstall or (u)ninstall: "
read install_uninstall
echo
case $install_uninstall in
i|I)mount_rw
if [ ! -d "/sqlite_stmt_journals" ]; then
mkdir /sqlite_stmt_journals
fi
if [ ! -d "/data/TrimDropOff" ]; then
mkdir /data/TrimDropOff
chmod 755 /data/TrimDropOff
fi;;
u|U)mount_rw
rm /system/etc/init.d/Z99TrimDropOff_Sync 2>/dev/null
rm /system/etc/init.d/07TrimDropOff_Cron 2>/dev/null
rm /system/xbin/trimdrop 2>/dev/null
rm -rf /data/TrimDropOff 2>/dev/null
echo "Are you using cron.d for any other services?"
echo -n "Input (y)es or (n)o: "
read crond_use
echo
case $crond_use in
y|Y)sed '/TrimDropOff/d' -i /system/etc/cron.d/crontabs/root 2>/dev/null;;
n|N)rm -rf /system/etc/cron.d 2>/dev/null;;
*)input_error;;
esac
mount_ro
echo "All done. You can close your app now."
echo "Reboot your device to stop all processes."
exit 0;;
*)input_error;;
esac

wifi_only(){
cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
#!/system/bin/sh

tdo_time(){
while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
while [ 1 ]; do
AWAKE=\`cat /sys/power/wait_for_fb_wake\`
if [ "\$AWAKE" = "awake" ]; then
exec 1>/data/TrimDropOff/Awake.log
svc wifi enable
echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
echo "PIDs:"
pgrep -f TrimDrop
pidls=\`pgrep -f TrimDrop\`
echo "Verify Correct PIDs:"
for i in \$pidls; do
cat /proc/\$i/cmdline
done
echo ""
echo "RAM Usage:"
for i in \$pidls; do
dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
done
fi
SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
if [ "\$SLEEPING" = "sleeping" ]; then
exec 1>/data/TrimDropOff/Sleep.log
echo "\$(date +"%r %Y.%m.%d"): Offing."
svc wifi disable
fi
done
}
if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
tdo_time &
fi
exit 0
EOF
}

fstrim_only(){
cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
#!/system/bin/sh

tdo_time(){
while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
while [ 1 ]; do
AWAKE=\`cat /sys/power/wait_for_fb_wake\`
if [ "\$AWAKE" = "awake" ]; then
exec 1>/data/TrimDropOff/Awake.log
echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
echo "PIDs:"
pgrep -f TrimDrop
pidls=\`pgrep -f TrimDrop\`
echo "Verify Correct PIDs:"
for i in \$pidls; do
cat /proc/\$i/cmdline
done
echo ""
echo "RAM Usage:"
for i in \$pidls; do
dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
done
fi
SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
if [ "\$SLEEPING" = "sleeping" ]; then
exec 1>/data/TrimDropOff/Sleep.log
echo "\$(date +"%r %Y.%m.%d"): Trimming."
echo "/system:"
busybox sync
fstrim -v /system
echo "/data:"
busybox sync
fstrim -v /data
echo "/cache:"
busybox sync
fstrim -v /cache
fi
done
}
if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
tdo_time &
fi
exit 0
EOF
}

drop_only(){
cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
#!/system/bin/sh

tdo_time(){
while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
while [ 1 ]; do
AWAKE=\`cat /sys/power/wait_for_fb_wake\`
if [ "\$AWAKE" = "awake" ]; then
exec 1>/data/TrimDropOff/Awake.log
echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
echo "PIDs:"
pgrep -f TrimDrop
pidls=\`pgrep -f TrimDrop\`
echo "Verify Correct PIDs:"
for i in \$pidls; do
cat /proc/\$i/cmdline
done
echo ""
echo "RAM Usage:"
for i in \$pidls; do
dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
done
fi
SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
if [ "\$SLEEPING" = "sleeping" ]; then
exec 1>/data/TrimDropOff/Sleep.log
echo "\$(date +"%r %Y.%m.%d"): Dropping."
echo "drop caches:"
busybox sync
busybox sysctl -w vm.drop_caches=3
fi
done
}
if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
tdo_time &
fi
exit 0
EOF
}

wifi_fstrim(){
cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
#!/system/bin/sh

tdo_time(){
while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
while [ 1 ]; do
AWAKE=\`cat /sys/power/wait_for_fb_wake\`
if [ "\$AWAKE" = "awake" ]; then
exec 1>/data/TrimDropOff/Awake.log
svc wifi enable
echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
echo "PIDs:"
pgrep -f TrimDrop
pidls=\`pgrep -f TrimDrop\`
echo "Verify Correct PIDs:"
for i in \$pidls; do
cat /proc/\$i/cmdline
done
echo ""
echo "RAM Usage:"
for i in \$pidls; do
dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
done
fi
SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
if [ "\$SLEEPING" = "sleeping" ]; then
exec 1>/data/TrimDropOff/Sleep.log
echo "\$(date +"%r %Y.%m.%d"): Trimming, Offing."
echo "/system:"
busybox sync
fstrim -v /system
echo "/data:"
busybox sync
fstrim -v /data
echo "/cache:"
busybox sync
fstrim -v /cache
svc wifi disable
fi
done
}
if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
tdo_time &
fi
exit 0
EOF
}

wifi_drop(){
cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
#!/system/bin/sh

tdo_time(){
while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
while [ 1 ]; do
AWAKE=\`cat /sys/power/wait_for_fb_wake\`
if [ "\$AWAKE" = "awake" ]; then
exec 1>/data/TrimDropOff/Awake.log
svc wifi enable
echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
echo "PIDs:"
pgrep -f TrimDrop
pidls=\`pgrep -f TrimDrop\`
echo "Verify Correct PIDs:"
for i in \$pidls; do
cat /proc/\$i/cmdline
done
echo ""
echo "RAM Usage:"
for i in \$pidls; do
dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
done
fi
SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
if [ "\$SLEEPING" = "sleeping" ]; then
exec 1>/data/TrimDropOff/Sleep.log
echo "\$(date +"%r %Y.%m.%d"): Dropping, Offing."
echo "drop caches:"
busybox sync
busybox sysctl -w vm.drop_caches=3
svc wifi disable
fi
done
}
if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
tdo_time &
fi
exit 0
EOF
}

fstrim_drop(){
cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
#!/system/bin/sh

tdo_time(){
while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
while [ 1 ]; do
AWAKE=\`cat /sys/power/wait_for_fb_wake\`
if [ "\$AWAKE" = "awake" ]; then
exec 1>/data/TrimDropOff/Awake.log
echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
echo "PIDs:"
pgrep -f TrimDrop
pidls=\`pgrep -f TrimDrop\`
echo "Verify Correct PIDs:"
for i in \$pidls; do
cat /proc/\$i/cmdline
done
echo ""
echo "RAM Usage:"
for i in \$pidls; do
dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
done
fi
SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
if [ "\$SLEEPING" = "sleeping" ]; then
exec 1>/data/TrimDropOff/Sleep.log
echo "\$(date +"%r %Y.%m.%d"): Trimming, Dropping."
echo "/system:"
busybox sync
fstrim -v /system
echo "/data:"
busybox sync
fstrim -v /data
echo "/cache:"
busybox sync
fstrim -v /cache
echo "drop caches:"
busybox sync
busybox sysctl -w vm.drop_caches=3
fi
done
}
if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
tdo_time &
fi
exit 0
EOF
}

wifi_fstrim_drop(){
cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
#!/system/bin/sh

tdo_time(){
while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
while [ 1 ]; do
AWAKE=\`cat /sys/power/wait_for_fb_wake\`
if [ "\$AWAKE" = "awake" ]; then
exec 1>/data/TrimDropOff/Awake.log
svc wifi enable
echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
echo "PIDs:"
pgrep -f TrimDrop
pidls=\`pgrep -f TrimDrop\`
echo "Verify Correct PIDs:"
for i in \$pidls; do
cat /proc/\$i/cmdline
done
echo ""
echo "RAM Usage:"
for i in \$pidls; do
dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
done
fi
SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
if [ "\$SLEEPING" = "sleeping" ]; then
exec 1>/data/TrimDropOff/Sleep.log
echo "\$(date +"%r %Y.%m.%d"): Trimming, Dropping, Offing."
echo "/system:"
busybox sync
fstrim -v /system
echo "/data:"
busybox sync
fstrim -v /data
echo "/cache:"
busybox sync
fstrim -v /cache
echo "drop caches:"
busybox sync
busybox sysctl -w vm.drop_caches=3
svc wifi disable
fi
done
}
if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
tdo_time &
fi
exit 0
EOF
}

echo "Do you want to sync fstrim, drop_caches=3, and/or"
echo "wifi with sleep?"
echo "WARNING: This will cause init.d scripts with a"
echo "priority lower than Z99 to NOT execute."
echo -n "Input (y)es or (n)o: "
read TDOsync
echo
case $TDOsync in
y|Y)echo "Which function(s) would you like to sync with sleep?"
echo "Input 1 for wifi only, 2 for fstrim only,"
echo "3 for drop_caches only, 4 for wifi and fstrim"
echo "5 for wifi and drop, 6 for fstrim and drop, or"
echo -n "7 for all: "
read sync_opt
echo
case $sync_opt in
1)wifi_only;;
2)fstrim_only;;
3)drop_only;;
4)wifi_fstrim;;
5)wifi_drop;;
6)fsrim_drop;;
7)wifi_fstrim_drop;;
*)input_error;;
esac
chmod 755 /system/etc/init.d/Z99TrimDropOff_Sync;;
n|N);;
*)input_error;;
esac

only_fstrim(){
cat > /data/TrimDropOff/TrimDropOff_Cron << EOF
#!/system/bin/sh

# This script was authored by Defiant07 @ xda. Feel free to use it as you see fit, but please give proper credits.
# Read Karl Marx.

exec 1>/data/TrimDropOff/CronRan.log
echo "\$(date +"%r %Y.%m.%d"): Trimming."
echo "/system:"
busybox sync
fstrim -v /system
echo "/data:"
busybox sync
fstrim -v /data
echo "/cache:"
busybox sync
fstrim -v /cache
exit 0
EOF
}

only_drop(){
cat > /data/TrimDropOff/TrimDropOff_Cron << EOF
#!/system/bin/sh

# This script was authored by Defiant07 @ xda. Feel free to use it as you see fit, but please give proper credits.
# Read Karl Marx.

exec 1>/data/TrimDropOff/CronRan.log
echo "\$(date +"%r %Y.%m.%d"): Dropping."
echo "drop caches:"
busybox sync
busybox sysctl -w vm.drop_caches=3
exit 0
EOF
}

both_funct(){
cat > /data/TrimDropOff/TrimDropOff_Cron << EOF
#!/system/bin/sh

# This script was authored by Defiant07 @ xda. Feel free to use it as you see fit, but please give proper credits.
# Read Karl Marx.

exec 1>/data/TrimDropOff/CronRan.log
echo "\$(date +"%r %Y.%m.%d"): Trimming, Dropping."
echo "/system:"
busybox sync
fstrim -v /system
echo "/data:"
busybox sync
fstrim -v /data
echo "/cache:"
busybox sync
fstrim -v /cache
echo "drop caches:"
busybox sync
busybox sysctl -w vm.drop_caches=3
exit 0
EOF
}

cron_starter(){
cat > /system/etc/init.d/07TrimDropOff_Cron << EOF
#!/system/bin/sh

# This script was authored by Defiant07 @ xda. Feel free to use it as you see fit, but please give proper credits.
# Read Karl Marx.

tdo_time(){
while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
crond
exec 1>/data/TrimDropOff/CronBoot.log
echo "\$(date +"%r %Y.%m.%d"): cron.d service started."
echo "PIDs:"
pgrep crond
pidls=\`pgrep crond\`
echo "Verify Correct PIDs:"
for i in \$pidls; do
cat /proc/\$i/cmdline
done
echo ""
echo "RAM Usage:"
for i in \$pidls; do
dumpsys meminfo | grep \$i | grep -m 1 crond
done
}
if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
else exec > /data/TrimDropOff/Cron_BootErrors.log 2>&1
tdo_time &
fi
exit 0
EOF
}

echo "Do you want to run fstrim and/or drop_caches"
echo "on a schedule?"
echo -n "Input (y)es or (n)o: "
read sched_opt
echo
case $sched_opt in
y|Y)echo "Which function do you want to schedule?"
echo "Input (f)strim only, (d)rop_caches only,"
echo -n "or (b)oth: "
read funct_opt
echo
case $funct_opt in
f|F)only_fstrim;;
d|D)only_drop;;
b|B)both_funct;;
*)input_error;;
esac
chmod 755 /data/TrimDropOff/TrimDropOff_Cron
echo "Do you want to schedule the function(s)"
echo "on an hourly or daily basis?"
echo -n "Input (h)ourly or (d)aily: "
read sched_opt
echo
if [ ! -d "/system/etc/cron.d" ]; then
mkdir /system/etc/cron.d
chmod 755 /system/etc/cron.d
fi
if [ ! -d "/system/etc/cron.d/crontabs" ]; then
mkdir /system/etc/cron.d/crontabs
chmod 755 /system/etc/cron.d/crontabs
fi
cron_starter
chmod 755 /system/etc/init.d/07TrimDropOff_Cron
case $sched_opt in
h|H)echo "Input 1 to run every hour, 2 to run every two hours,"
echo -n "3 to run every three hours...etc: "
read hour_opt
echo
if [ ! "`echo $hour_opt | awk '!/[^0-9]/'`" ]; then
input_error
fi
if [ -f "/system/etc/cron.d/crontabs/root" ]; then
echo "0 */$hour_opt * * * nohup /data/TrimDropOff/TrimDropOff_Cron" >> /system/etc/cron.d/crontabs/root
else
echo "0 */$hour_opt * * * nohup /data/TrimDropOff/TrimDropOff_Cron" > /system/etc/cron.d/crontabs/root
fi
chmod 755 /system/etc/cron.d/crontabs/root;;
d|D)echo "Input 0 to run at midnight every day,"
echo "1 to run at 1:00 am...13 to run at 1:00 pm"
echo -n "...etc...up to 23: "
read daily_opt
echo
if [ ! "`echo $daily_opt | awk '!/[^0-9]/ && $1<=23'`" ]; then
input_error
fi
if [ -f "/system/etc/cron.d/crontabs/root" ]; then
echo "0 $daily_opt * * * nohup /data/TrimDropOff/TrimDropOff_Cron" >> /system/etc/cron.d/crontabs/root
else
echo "0 $daily_opt * * * nohup /data/TrimDropOff/TrimDropOff_Cron" > /system/etc/cron.d/crontabs/root
fi
chmod 755 /system/etc/cron.d/crontabs/root;;
*)input_error;;
esac;;
n|N);;
*)input_error;;
esac

cat > /system/xbin/trimdrop << EOF
#!/system/bin/sh

# This script was authored by Defiant07 @ xda. Feel free to use it as you see fit, but please give proper credits.
# Read Karl Marx.

clear

trimmer(){
echo "/system:"
busybox sync
fstrim -v /system
echo "/data:"
busybox sync
fstrim -v /data
echo "/cache:"
busybox sync
fstrim -v /cache
}

dropper(){
echo "drop caches:"
busybox sync
busybox sysctl -w vm.drop_caches=3
}

echo -n "Do you want to run (f)strim, (d)rop_caches=3, or (b)oth? "
read funct_opt
echo
case \$funct_opt in
f|F)trimmer;;
d|D)dropper;;
b|B)trimmer
dropper;;
*)echo "That is not a valid input...try again...bye :p."
exit 69;;
esac
echo
echo "All done...enjoy! You can close your app now."

exit 0
EOF
chmod 755 /system/xbin/trimdrop
mount_ro

echo "In addition to making the files required by"
echo "your desired configuration, I have also made"
echo "an on-the-fly script to run fstrim and/or"
echo "drop_caches on-demand."
echo "To use it, in terminal do: su -c trimdrop"
echo
sleep 3
echo "Reboot your device to start your desired services."
echo
sleep 3
echo "If you want to know how to verify everything"
echo "is working, read the script's OP (FFS)!"
echo
sleep 5
echo "All done...enjoy! You can close your app now."

exit 0

Changelog:
v2.0
  • made in to installer script
  • added cron options
  • added bootloop precautions to the init.d scripts (should make it compatible with all devices that meet the requirments)
  • the on-the-fly script, trimdrop, now allows user to choose fstrim and/or drop_caches=3
  • added more syncs to further ensure no data is lost
  • a bunch of other stuff I probably forget
v2.1
  • bug fixes - fixed issue if using only sync option (missing directory); fixed display of irrelevant errors in uninstall routine
  • cleaned code a bit (reduced redundancy)

Download History:
  • Defiant07s_TrimDropOff.zip - [Click for QR Code] (1.6 KB, 162 views)
  • Defiant07s_TrimDropOff_v2.0_[NOT_FLASHABLE].zip - [Click for QR Code] (3.0 KB, 89 views)

Credits:
  • Big thanks to @zeppelinrox, @dk_zero-cool, & @gu5t3r for their contributions to portions of this script (see the code of my other script SwapItOn for detailed citations).
  • Much thanks to @mdamaged for spotting the issue with sync init.d script and his note regarding syncing data.

Don't forget to click THANKS and RATE 5 STARS if you found this useful :highfive:.

peep my other script SwapItOn :p

Update to v2.1 if you were only using the sync option.
If you were using both the sync and schedule options or only the schedule option there is no need to update; the bug I found would not effect you.​
 
Last edited:

defiant07

Senior Member
Feb 26, 2013
410
496
Thanks, sounds interesting. I'm assuming the zip can be flashed right after flashing a new rom? :)

As you were informed the zip is NOT flashable. If there is sufficient interest (say a 100 downloads) I'll make it flashable/aroma.

Is compatible with custom kernel? Franco in my case

vía n7II r-paco

Yes, it should be compatible...the fstrim utility is part of the rom (it should be in all nexus 4.3+ roms).

Will performing trimming operations too frequently cause additional flash memory degradation?

No, to my limited knowledge it should not be harmful (in fact it should increase lifespan - google "fstrim lifespan"). Did a quick google search but could not find anything definitive/reliable regarding frequency...what I did see seemed to suggest 'no' though.

If you are concerned about the frequency, you could not install the init.d script and just use the on-the-fly script, trimdrop, to trim on-demand. Should there be interest and if I have the motivation and time, I have been thinking about making this in to an installer script and/or aroma zip with cron-based options so it could be scheduled hourly, daily, or weekly.
 
Last edited:

defiant07

Senior Member
Feb 26, 2013
410
496
Scheduling options would be awesome!


Seems there is a decent amount of interest (almost 100 downloads already :)...thanks peeps), as such I'll add options and make things more configurable.

Regarding scheduling, I was thinking of doing hourly, daily (with ability to choose time), and weekly (with ability to choose day and time) options. Would every other hour or some other setting be desirable?

Regarding installation, what would be the preferred method, an installer script (e.g. V6 SuperCharger) or AROMA? Flashable zips would be another option, but would have less options/be less configurable.

Gimme some feedback and I'll put something together in the next week or two depending on work and my motivation :p.
 

creeve4

Senior Member
Jan 5, 2011
2,871
596
Bountiful
Seems there is a decent amount of interest (almost 100 downloads already :)...thanks peeps), as such I'll add options and make things more configurable.

Regarding scheduling, I was thinking of doing hourly, daily (with ability to choose time), and weekly (with ability to choose day and time) options. Would every other hour or some other setting be desirable?

Regarding installation, what would be the preferred method, an installer script (e.g. V6 SuperCharger) or AROMA? Flashable zips would be another option, but would have less options/be less configurable.

Gimme some feedback and I'll put something together in the next week or two depending on work and my motivation :p.

My 2 cents:
I would choose a daily option for my device.
I prefer Aroma over a script, but if you cannot get the customization you want with Aroma, then by all means go with a script.

Thanks again for the script and willingness to make it even better!
 
  • Like
Reactions: defiant07

mdamaged

Senior Member
Oct 16, 2013
2,109
1,448
South of Heaven
Moto G5 Plus
Google Pixel 4a
Thanks for the scripts, I time my startup, and this improved startup time by about 3-4secs, among other noticible improvements, apparently the stock OS does not run fstrim enough, initial operations freed several gigs on the data partition, and hundreds of megs on the others...
 
  • Like
Reactions: defiant07

jubei_mitsuyoshi

Senior Member
Mar 23, 2013
50
92
Im going to turn this into a cron job, that will take care of scheduling, unless anyone else gets there first ( please lol )
Will give it a go in its present form, whats its resource footprint just sitting there waiting for screen off ?
Can we trigger the action from the screen off event ? or some other interupt type way ?
Great script by the way, your bash is damn site better than mine, jealous lol
 

defiant07

Senior Member
Feb 26, 2013
410
496
wasn't this a nexus 7 2012 issue and fixed in the new version 2013?

Yes, I think this is true to a degree...it was more of a problem on the 2012 and other nexus devices. See the links in the OP for the conditions that need to be met for fstrim to autorun...for some users (myself included) the conditions will seldom if ever be met. Also see @mdamaged post; I get similar results the first time fstrim is initiated by my script after each boot...subsequent runs normally only frees up memory on /data.

My 2 cents:
I would choose a daily option for my device.
I prefer Aroma over a script, but if you cannot get the customization you want with Aroma, then by all means go with a script.

Thanks again for the script and willingness to make it even better!

Okay will get to making an AROMA package...it will be my first, but it looks easy enough :fingers-crossed:...gimme a week or two to put it together and fully test.

Thanks for the scripts, I time my startup, and this improved startup time by about 3-4secs, among other noticible improvements, apparently the stock OS does not run fstrim enough, initial operations freed several gigs on the data partition, and hundreds of megs on the others...

Thanks for the feedback. I get similar results.

Im going to turn this into a cron job, that will take care of scheduling, unless anyone else gets there first ( please lol )
Will give it a go in its present form, whats its resource footprint just sitting there waiting for screen off ?
Can we trigger the action from the screen off event ? or some other interupt type way ?
Great script by the way, your bash is damn site better than mine, jealous lol

See the first post on this page and my response to @creeve4 and @imfun in this post. I will make an AROMA package with cron options for fstrim and drop_caches=3.

However, should you feel ambitious and beat me to it, props to you...I will give you full credit in the OP and link your post as the d/l source so you should get the 'thanks' too.

Regarding triggering with screen on/off or some other event: It can probably be done, but I it's beyond my knowledge (screen on/off was actually the first trigger event I looked in to using, but despite fairly extensive searching I could not find how to detect it).

Regarding resource footprint: Read the OP (usage section) it explains where to find the log which contains this info and how to do it via terminal (should you not trust me :p)...also see OP (benefits section): in all my testing I have never seen it use more that .8 mb, but most of the time it is less than .2 mb.
 
Last edited:

imfun

Senior Member
Mar 22, 2012
70
13
Okay will get to making an AROMA package...it will be my first, but it looks easy enough :fingers-crossed:...gimme a week or two to put it together and fully test.
Can't wait already, because after whole day or two, hard usage of my nexus 7 tablet, the tablet starts to get laggy. I can see this on web browsing, touch press delay time, and onyl rebooting seems to help... Hope after istaling this will solve the problems :)
 
  • Like
Reactions: defiant07

jubei_mitsuyoshi

Senior Member
Mar 23, 2013
50
92
ohhh no dont want any credit lol lol, i have turned it into a cron job quite simply by adding it to the cron initilising script

Code:
###########
# IMPORTS #
###########
. /system/etc/init.d.cfg

#############
# FUNCTIONS #
#############

symlink_system_bin() {
	# crond has "/bin/sh" hardcoded
	if busybox [ ! -h /bin ]
	then
		mount -o remount,rw rootfs /
		busybox ln -s /system/bin /bin
		mount -o remount,ro rootfs /
	fi
}

export_timezone() {
	# set timezone (if you're not between -0500 and -0800 you get PST)
	# todo - support other timezones
	timezone=`date +%z`
	if busybox [ $timezone = "-0800" ]; then
	  TZ=PST8PDT
	elif busybox [ $timezone = "-0700" ]; then
	  TZ=MST7MDT
	elif busybox [ $timezone = "-0600" ]; then
	  TZ=CST6CDT
	elif busybox [ $timezone = "-0500" ]; then
	  TZ=EST5EDT
	else
		TZ=PST8PDT
	fi
	export TZ
}

set_crontab() {
	# use /data/cron, call the crontab file "root"
	if busybox [ -e /data/cron/root ]
	then
		mkdir -p /data/cron
		cat > /data/cron/root << EOF
0 20 * * * sync; echo 3 > /proc/sys/vm/drop_caches
0 20 * * * sync; fstrim -v /system
0 20 * * * sync; fstrim -v /data
0 20 * * * sync; fstrim -v /cache

01 * * * * busybox run-parts /system/etc/cron/cron.hourly
02 4 * * * busybox run-parts /system/etc/cron/cron.daily
22 4 * * 0 busybox run-parts /system/etc/cron/cron.weekly
EOF
	fi
	busybox crond -c /data/cron
}

########
# MAIN #
########

if $enable_cron -a is_busybox_applet_available crond
then
	symlink_system_bin
	export_timezone
	set_crontab
fi

adding the lines

Code:
0 20 * * * sync; echo 3 > /proc/sys/vm/drop_caches
0 20 * * * sync; fstrim -v /system
0 20 * * * sync; fstrim -v /data
0 20 * * * sync; fstrim -v /cache

should drop the caches and fstrim every 8 hours, oviously set to anything you want.

i also stuck it in boot at the end

/system/etc/init.d/92jubei

Code:
#!/system/bin/sh

if $file_system_speedups
then
	busybox mount -o remount,noatime,barrier=0,nobh /system
	busybox mount -o remount,noatime /data
	busybox mount -o remount,noatime,barrier=0,nobh /cache
else
	busybox mount -o remount,noatime,nobh /system
	busybox mount -o remount,noatime /data
	busybox mount -o remount,noatime,nobh /cache
fi

echo "$(date +"%r %Y.%m.%d"): Trimming, Dropping."
busybox sync
echo "/system:"
fstrim -v /system
echo "/data:"
fstrim -v /data
echo "/cache:"
fstrim -v /cache
echo "drop caches:"
busybox sysctl -w vm.drop_caches=3
exit 0

For an aroma script you will prob have to stick the file in /system/etc/cron/cron.hourly, daily, weekly and just give peeps that choice, will be most simple way. Ps not a fan of aroma lol
 
  • Like
Reactions: defiant07

mdamaged

Senior Member
Oct 16, 2013
2,109
1,448
South of Heaven
Moto G5 Plus
Google Pixel 4a
Ok, I should have spotted this issue right away, but did not, so here goes. It seems the use of while loop in the script in the OP causes any scripts with a lower priority in init.d to never get ran, if the script in the OP is the only one in your init.d this does not matter, nor should it matter if you have at boot script with a higher priority (they get ran before the OPs script).

I run the ElementalX kernel which depends on a init.d to initialize some parameters for the kernel, with this script in init.d they never get initialized, in my case this resulted in some things not 'taking' such as the battery life extender, which on my device, is set to stop charging at 4100mv, however, since the while loop kept the ElementalX init.d from running, it kept charging to ~4300mv, this is how I noticed (actually none of my settings wrt ElementalX were being initialized, but this symptom was most pronounced).

A simple fix would be to move up the priority of the ElementalX init.d script, but this would have to be done after each flash, and frankly since I run Tasker anyway, I saw no need for this, what I did was remove the OPs script from init.d and simply made a very simple task in Tasker to run /system/xbin/trimdrop when display goes off, it could just as easily be a time event.

Anyways, hope that helps someone who may come across this with other kernels, or other at-boot scripts which depend on being ran before the OPs script.

Again, thanks to the OP for his work. Also, I added another sync just before the drop caches, since the state of dirtyness could change after the fstrims.
 
Last edited:
  • Like
Reactions: defiant07

Top Liked Posts

  • There are no posts matching your filters.
  • 24
    Updated 03.26.14 - Released v2.1 - bug fixes and code cleaned

    Introduction:
    I am by no means a developer. I am just an android enthusiast who has learned a bit of bash. The reason I made this script was that settings>>wifi>>advanced was not promptly turning wifi off when my device would sleep; sometimes it would not turn off at all. So I figured since I am making a script to resolve this issue I might as well add a couple of other functions as well. To this end I noticed some people saying THIS APP was helpful and I missed the Flush-O-Matic script from V6 SuperCharger so I added fstrim and drop_caches=3 to the script.

    What will this do?
    • The script will allow you to sync wifi, fstrim, and/or drop_caches=3 with sleep and/or it will allow you to schedule fstrim and/or drop_caches=3 using crond. The scheduling option can work on either a hourly (you can choose to run desired programs every hour on the hour, every two hours on the hour, every 3 hours on the hour, etc) or daily basis (you can choose to run desired programs at a given time on the hour).
    • Both the sync and schedule options will load themselves in to memory each boot and each time your device goes to sleep and/or when scheduled the scripts will depending on your options: (1) sync your data so as to ensure no data is lost; (2) TRIM your /system, /data, and /cache partitions; (3) DROP CACHES = 3; and (4) turn off wifi.
    • In addition, there is also an on-the-fly script to manually trim partitions and drop caches when desired.

    Benefits:
    • Reduce lag/improve i/o efficiency (see THIS and THIS).
    • Although android automatically invokes fstrim when certain conditions are met, these criteria could seldom if ever be met depending upon your usage style. The init.d script should ensure fstrim is invoked more frequently for most users.
    • Should use less ram than apps that perform similar functions (I say should because I have never used such apps, but I imagine they consume more that .2-.5 mb of ram).

    Requirements:

    Warning/Disclaimer:
    Although these scripts function as intended on my device – Nexus 7 (2013), SlimKat (weekly), ElementalX...Use at your own risk. Neither I nor XDA are responsible for any possible deleterious effects.

    Known Issues/Bugs:
    • If you use the sync option, scripts with a lower priority than Z99 will not execute.
    • The log files don't always display as intended...dunno why...any help/suggestions would be appreciated.
    • Let me know if you find any others :p.

    Install, Usage/Verification, & Uninstall:
    Install -
    1. Note: If you use crond for other tasks, both the install and uninstall routine account for this potential contigency and should leave your other crond tasks uneffects.
    2. make a nandroid backup
    3. download the zip (<<NOT flashable) attached to this post
    4. extract the zip’s contents
    5. if you were/are using the first version of this script manually delete: /etc/init.d/07TrimDropOff, /data/TrimDropOff_Awake.log, and /data/TrimDropOff_Sleep.log
    6. run TrimDropOffInstaller with superuser permission via terminal or script manager.
    7. follow the scripts prompts
    8. reboot
    9. enjoy

    Usage/Verification -
    • Assuming you have followed the install procedure, next, put your device to sleep and then wake it if you are using the sync option.
    • Now check the various logs in /data/TrimDropOff. The logs will show the time, the script’s PIDs, the path of the PIDs (just to double-check the PIDs are correct), the ram used by the PIDs, action(s) preformed (amount trimmed from each partition and/or if drop_cahes was run), or errors.
    • If you want verify manually via terminal do [pgrep -f TrimDrop] for the sync option or [pgrep crond] for the scheduling option to get the PIDs, do [cat /proc/PID/cmdline] for each PID to verify it truly belongs to Z99TrimDropOff or crond, and do [dumpsys meminfo | grep PID] for each PID to verify ram usage (this command will yield duplicates, which can be disregarded and may output undesired additional results, which can be filtered by looking through the results for the relevant PID).
    • To use the on-the-fly script to trim and/or drop as desired, in terminal do [su -c trimdrop].
    • Should you want to reconfigure your setup, uninstall before reinstalling to avoid potential issues.

    Uninstall -
    • Note: If you use crond for other tasks, both the install and uninstall routine account for this potential contigency and should leave your other crond tasks uneffects.
    • Rerun TrimDropOffInstaller with superuser permission and use uninstall option at the beginning of the script.
    • Reboot and all will be back to as it was before.

    To-Do List:
    • Make in to an AROMA package.
    • I don't know, you tell me :).

    Code:
    #!/system/bin/sh

    # This script was authored by Defiant07 @ xda. Feel free to use it as you see fit, but please give proper credits.
    # Big thanks to zeppelinrox, dk_zero-cool, & gu5t3r @ xda for their contributions to portions of this script (see the code of my other script SwapItOn @ xda for detailed citations).
    # Read Karl Marx.

    input_error(){
    echo "That is not a valid input...try again...bye :p."
    exit 69
    }

    mount_rw(){
    mount -o remount,rw / 2>/dev/null
    mount -o remount,rw rootfs 2>/dev/null
    busybox mount -o remount,rw / 2>/dev/null
    busybox mount -o remount,rw rootfs 2>/dev/null
    mount -o remount,rw /system 2>/dev/null
    busybox mount -o remount,rw /system 2>/dev/null
    busybox mount -o remount,rw $(busybox mount | awk '/system /{print $1,$3}') 2>/dev/null
    }

    mount_ro(){
    mount -o remount,ro / 2>/dev/null
    mount -o remount,ro rootfs 2>/dev/null
    busybox mount -o remount,ro / 2>/dev/null
    busybox mount -o remount,ro rootfs 2>/dev/null
    mount -o remount,ro /system 2>/dev/null
    busybox mount -o remount,ro /system 2>/dev/null
    busybox mount -o remount,ro $(busybox mount | awk '/system /{print $1,$3}') 2>/dev/null
    }

    clear
    if [ ! "`busybox`" ]; then
    echo "Missing busybox...try again...bye :p."
    exit 69
    fi
    id=$(id); id=${id#*=}; id=${id%%[\( ]*}
    if [ "$id" = "0" ] || [ "$id" = "root" ]; then
    echo "" 1>/dev/null
    else
    echo "Not running as root...try again...bye :p."
    exit 69
    fi
    if [ ! -d /etc/init.d ]; then
    echo "Missing /etc/init.d...try again...bye :p."
    exit 69
    fi
    if [ ! "`grep -r fstrim /system/bin`" ] && [ ! "`grep -r fstrim /system/xbin`" ]; then
    echo "Missing fstrim...try again...bye :p."
    exit 69
    fi
    echo "Do you want to install or uninstall TrimDropOff?"
    echo "Note: If you are rerunning this script to"
    echo "reconfigure your setup, uninstall first."
    echo -n "Input (i)nstall or (u)ninstall: "
    read install_uninstall
    echo
    case $install_uninstall in
    i|I)mount_rw
    if [ ! -d "/sqlite_stmt_journals" ]; then
    mkdir /sqlite_stmt_journals
    fi
    if [ ! -d "/data/TrimDropOff" ]; then
    mkdir /data/TrimDropOff
    chmod 755 /data/TrimDropOff
    fi;;
    u|U)mount_rw
    rm /system/etc/init.d/Z99TrimDropOff_Sync 2>/dev/null
    rm /system/etc/init.d/07TrimDropOff_Cron 2>/dev/null
    rm /system/xbin/trimdrop 2>/dev/null
    rm -rf /data/TrimDropOff 2>/dev/null
    echo "Are you using cron.d for any other services?"
    echo -n "Input (y)es or (n)o: "
    read crond_use
    echo
    case $crond_use in
    y|Y)sed '/TrimDropOff/d' -i /system/etc/cron.d/crontabs/root 2>/dev/null;;
    n|N)rm -rf /system/etc/cron.d 2>/dev/null;;
    *)input_error;;
    esac
    mount_ro
    echo "All done. You can close your app now."
    echo "Reboot your device to stop all processes."
    exit 0;;
    *)input_error;;
    esac

    wifi_only(){
    cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
    #!/system/bin/sh

    tdo_time(){
    while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
    while [ 1 ]; do
    AWAKE=\`cat /sys/power/wait_for_fb_wake\`
    if [ "\$AWAKE" = "awake" ]; then
    exec 1>/data/TrimDropOff/Awake.log
    svc wifi enable
    echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
    echo "PIDs:"
    pgrep -f TrimDrop
    pidls=\`pgrep -f TrimDrop\`
    echo "Verify Correct PIDs:"
    for i in \$pidls; do
    cat /proc/\$i/cmdline
    done
    echo ""
    echo "RAM Usage:"
    for i in \$pidls; do
    dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
    done
    fi
    SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
    if [ "\$SLEEPING" = "sleeping" ]; then
    exec 1>/data/TrimDropOff/Sleep.log
    echo "\$(date +"%r %Y.%m.%d"): Offing."
    svc wifi disable
    fi
    done
    }
    if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
    else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
    tdo_time &
    fi
    exit 0
    EOF
    }

    fstrim_only(){
    cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
    #!/system/bin/sh

    tdo_time(){
    while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
    while [ 1 ]; do
    AWAKE=\`cat /sys/power/wait_for_fb_wake\`
    if [ "\$AWAKE" = "awake" ]; then
    exec 1>/data/TrimDropOff/Awake.log
    echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
    echo "PIDs:"
    pgrep -f TrimDrop
    pidls=\`pgrep -f TrimDrop\`
    echo "Verify Correct PIDs:"
    for i in \$pidls; do
    cat /proc/\$i/cmdline
    done
    echo ""
    echo "RAM Usage:"
    for i in \$pidls; do
    dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
    done
    fi
    SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
    if [ "\$SLEEPING" = "sleeping" ]; then
    exec 1>/data/TrimDropOff/Sleep.log
    echo "\$(date +"%r %Y.%m.%d"): Trimming."
    echo "/system:"
    busybox sync
    fstrim -v /system
    echo "/data:"
    busybox sync
    fstrim -v /data
    echo "/cache:"
    busybox sync
    fstrim -v /cache
    fi
    done
    }
    if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
    else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
    tdo_time &
    fi
    exit 0
    EOF
    }

    drop_only(){
    cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
    #!/system/bin/sh

    tdo_time(){
    while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
    while [ 1 ]; do
    AWAKE=\`cat /sys/power/wait_for_fb_wake\`
    if [ "\$AWAKE" = "awake" ]; then
    exec 1>/data/TrimDropOff/Awake.log
    echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
    echo "PIDs:"
    pgrep -f TrimDrop
    pidls=\`pgrep -f TrimDrop\`
    echo "Verify Correct PIDs:"
    for i in \$pidls; do
    cat /proc/\$i/cmdline
    done
    echo ""
    echo "RAM Usage:"
    for i in \$pidls; do
    dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
    done
    fi
    SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
    if [ "\$SLEEPING" = "sleeping" ]; then
    exec 1>/data/TrimDropOff/Sleep.log
    echo "\$(date +"%r %Y.%m.%d"): Dropping."
    echo "drop caches:"
    busybox sync
    busybox sysctl -w vm.drop_caches=3
    fi
    done
    }
    if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
    else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
    tdo_time &
    fi
    exit 0
    EOF
    }

    wifi_fstrim(){
    cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
    #!/system/bin/sh

    tdo_time(){
    while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
    while [ 1 ]; do
    AWAKE=\`cat /sys/power/wait_for_fb_wake\`
    if [ "\$AWAKE" = "awake" ]; then
    exec 1>/data/TrimDropOff/Awake.log
    svc wifi enable
    echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
    echo "PIDs:"
    pgrep -f TrimDrop
    pidls=\`pgrep -f TrimDrop\`
    echo "Verify Correct PIDs:"
    for i in \$pidls; do
    cat /proc/\$i/cmdline
    done
    echo ""
    echo "RAM Usage:"
    for i in \$pidls; do
    dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
    done
    fi
    SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
    if [ "\$SLEEPING" = "sleeping" ]; then
    exec 1>/data/TrimDropOff/Sleep.log
    echo "\$(date +"%r %Y.%m.%d"): Trimming, Offing."
    echo "/system:"
    busybox sync
    fstrim -v /system
    echo "/data:"
    busybox sync
    fstrim -v /data
    echo "/cache:"
    busybox sync
    fstrim -v /cache
    svc wifi disable
    fi
    done
    }
    if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
    else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
    tdo_time &
    fi
    exit 0
    EOF
    }

    wifi_drop(){
    cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
    #!/system/bin/sh

    tdo_time(){
    while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
    while [ 1 ]; do
    AWAKE=\`cat /sys/power/wait_for_fb_wake\`
    if [ "\$AWAKE" = "awake" ]; then
    exec 1>/data/TrimDropOff/Awake.log
    svc wifi enable
    echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
    echo "PIDs:"
    pgrep -f TrimDrop
    pidls=\`pgrep -f TrimDrop\`
    echo "Verify Correct PIDs:"
    for i in \$pidls; do
    cat /proc/\$i/cmdline
    done
    echo ""
    echo "RAM Usage:"
    for i in \$pidls; do
    dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
    done
    fi
    SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
    if [ "\$SLEEPING" = "sleeping" ]; then
    exec 1>/data/TrimDropOff/Sleep.log
    echo "\$(date +"%r %Y.%m.%d"): Dropping, Offing."
    echo "drop caches:"
    busybox sync
    busybox sysctl -w vm.drop_caches=3
    svc wifi disable
    fi
    done
    }
    if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
    else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
    tdo_time &
    fi
    exit 0
    EOF
    }

    fstrim_drop(){
    cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
    #!/system/bin/sh

    tdo_time(){
    while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
    while [ 1 ]; do
    AWAKE=\`cat /sys/power/wait_for_fb_wake\`
    if [ "\$AWAKE" = "awake" ]; then
    exec 1>/data/TrimDropOff/Awake.log
    echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
    echo "PIDs:"
    pgrep -f TrimDrop
    pidls=\`pgrep -f TrimDrop\`
    echo "Verify Correct PIDs:"
    for i in \$pidls; do
    cat /proc/\$i/cmdline
    done
    echo ""
    echo "RAM Usage:"
    for i in \$pidls; do
    dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
    done
    fi
    SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
    if [ "\$SLEEPING" = "sleeping" ]; then
    exec 1>/data/TrimDropOff/Sleep.log
    echo "\$(date +"%r %Y.%m.%d"): Trimming, Dropping."
    echo "/system:"
    busybox sync
    fstrim -v /system
    echo "/data:"
    busybox sync
    fstrim -v /data
    echo "/cache:"
    busybox sync
    fstrim -v /cache
    echo "drop caches:"
    busybox sync
    busybox sysctl -w vm.drop_caches=3
    fi
    done
    }
    if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
    else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
    tdo_time &
    fi
    exit 0
    EOF
    }

    wifi_fstrim_drop(){
    cat > /system/etc/init.d/Z99TrimDropOff_Sync << EOF
    #!/system/bin/sh

    tdo_time(){
    while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
    while [ 1 ]; do
    AWAKE=\`cat /sys/power/wait_for_fb_wake\`
    if [ "\$AWAKE" = "awake" ]; then
    exec 1>/data/TrimDropOff/Awake.log
    svc wifi enable
    echo "\$(date +"%r %Y.%m.%d"): Waiting for screen to sleep. Confirming script in memory..."
    echo "PIDs:"
    pgrep -f TrimDrop
    pidls=\`pgrep -f TrimDrop\`
    echo "Verify Correct PIDs:"
    for i in \$pidls; do
    cat /proc/\$i/cmdline
    done
    echo ""
    echo "RAM Usage:"
    for i in \$pidls; do
    dumpsys meminfo | grep \$i | grep sh | grep -m 1 pid
    done
    fi
    SLEEPING=\`cat /sys/power/wait_for_fb_sleep\`
    if [ "\$SLEEPING" = "sleeping" ]; then
    exec 1>/data/TrimDropOff/Sleep.log
    echo "\$(date +"%r %Y.%m.%d"): Trimming, Dropping, Offing."
    echo "/system:"
    busybox sync
    fstrim -v /system
    echo "/data:"
    busybox sync
    fstrim -v /data
    echo "/cache:"
    busybox sync
    fstrim -v /cache
    echo "drop caches:"
    busybox sync
    busybox sysctl -w vm.drop_caches=3
    svc wifi disable
    fi
    done
    }
    if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
    else exec > /data/TrimDropOff/Sync_BootErrors.log 2>&1
    tdo_time &
    fi
    exit 0
    EOF
    }

    echo "Do you want to sync fstrim, drop_caches=3, and/or"
    echo "wifi with sleep?"
    echo "WARNING: This will cause init.d scripts with a"
    echo "priority lower than Z99 to NOT execute."
    echo -n "Input (y)es or (n)o: "
    read TDOsync
    echo
    case $TDOsync in
    y|Y)echo "Which function(s) would you like to sync with sleep?"
    echo "Input 1 for wifi only, 2 for fstrim only,"
    echo "3 for drop_caches only, 4 for wifi and fstrim"
    echo "5 for wifi and drop, 6 for fstrim and drop, or"
    echo -n "7 for all: "
    read sync_opt
    echo
    case $sync_opt in
    1)wifi_only;;
    2)fstrim_only;;
    3)drop_only;;
    4)wifi_fstrim;;
    5)wifi_drop;;
    6)fsrim_drop;;
    7)wifi_fstrim_drop;;
    *)input_error;;
    esac
    chmod 755 /system/etc/init.d/Z99TrimDropOff_Sync;;
    n|N);;
    *)input_error;;
    esac

    only_fstrim(){
    cat > /data/TrimDropOff/TrimDropOff_Cron << EOF
    #!/system/bin/sh

    # This script was authored by Defiant07 @ xda. Feel free to use it as you see fit, but please give proper credits.
    # Read Karl Marx.

    exec 1>/data/TrimDropOff/CronRan.log
    echo "\$(date +"%r %Y.%m.%d"): Trimming."
    echo "/system:"
    busybox sync
    fstrim -v /system
    echo "/data:"
    busybox sync
    fstrim -v /data
    echo "/cache:"
    busybox sync
    fstrim -v /cache
    exit 0
    EOF
    }

    only_drop(){
    cat > /data/TrimDropOff/TrimDropOff_Cron << EOF
    #!/system/bin/sh

    # This script was authored by Defiant07 @ xda. Feel free to use it as you see fit, but please give proper credits.
    # Read Karl Marx.

    exec 1>/data/TrimDropOff/CronRan.log
    echo "\$(date +"%r %Y.%m.%d"): Dropping."
    echo "drop caches:"
    busybox sync
    busybox sysctl -w vm.drop_caches=3
    exit 0
    EOF
    }

    both_funct(){
    cat > /data/TrimDropOff/TrimDropOff_Cron << EOF
    #!/system/bin/sh

    # This script was authored by Defiant07 @ xda. Feel free to use it as you see fit, but please give proper credits.
    # Read Karl Marx.

    exec 1>/data/TrimDropOff/CronRan.log
    echo "\$(date +"%r %Y.%m.%d"): Trimming, Dropping."
    echo "/system:"
    busybox sync
    fstrim -v /system
    echo "/data:"
    busybox sync
    fstrim -v /data
    echo "/cache:"
    busybox sync
    fstrim -v /cache
    echo "drop caches:"
    busybox sync
    busybox sysctl -w vm.drop_caches=3
    exit 0
    EOF
    }

    cron_starter(){
    cat > /system/etc/init.d/07TrimDropOff_Cron << EOF
    #!/system/bin/sh

    # This script was authored by Defiant07 @ xda. Feel free to use it as you see fit, but please give proper credits.
    # Read Karl Marx.

    tdo_time(){
    while [ ! "\`ps | grep -m 1 [a]ndroid\`" ]; do sleep 10; done
    crond
    exec 1>/data/TrimDropOff/CronBoot.log
    echo "\$(date +"%r %Y.%m.%d"): cron.d service started."
    echo "PIDs:"
    pgrep crond
    pidls=\`pgrep crond\`
    echo "Verify Correct PIDs:"
    for i in \$pidls; do
    cat /proc/\$i/cmdline
    done
    echo ""
    echo "RAM Usage:"
    for i in \$pidls; do
    dumpsys meminfo | grep \$i | grep -m 1 crond
    done
    }
    if [ "\`ps | grep -m 1 [a]ndroid\`" ]; then tdo_time
    else exec > /data/TrimDropOff/Cron_BootErrors.log 2>&1
    tdo_time &
    fi
    exit 0
    EOF
    }

    echo "Do you want to run fstrim and/or drop_caches"
    echo "on a schedule?"
    echo -n "Input (y)es or (n)o: "
    read sched_opt
    echo
    case $sched_opt in
    y|Y)echo "Which function do you want to schedule?"
    echo "Input (f)strim only, (d)rop_caches only,"
    echo -n "or (b)oth: "
    read funct_opt
    echo
    case $funct_opt in
    f|F)only_fstrim;;
    d|D)only_drop;;
    b|B)both_funct;;
    *)input_error;;
    esac
    chmod 755 /data/TrimDropOff/TrimDropOff_Cron
    echo "Do you want to schedule the function(s)"
    echo "on an hourly or daily basis?"
    echo -n "Input (h)ourly or (d)aily: "
    read sched_opt
    echo
    if [ ! -d "/system/etc/cron.d" ]; then
    mkdir /system/etc/cron.d
    chmod 755 /system/etc/cron.d
    fi
    if [ ! -d "/system/etc/cron.d/crontabs" ]; then
    mkdir /system/etc/cron.d/crontabs
    chmod 755 /system/etc/cron.d/crontabs
    fi
    cron_starter
    chmod 755 /system/etc/init.d/07TrimDropOff_Cron
    case $sched_opt in
    h|H)echo "Input 1 to run every hour, 2 to run every two hours,"
    echo -n "3 to run every three hours...etc: "
    read hour_opt
    echo
    if [ ! "`echo $hour_opt | awk '!/[^0-9]/'`" ]; then
    input_error
    fi
    if [ -f "/system/etc/cron.d/crontabs/root" ]; then
    echo "0 */$hour_opt * * * nohup /data/TrimDropOff/TrimDropOff_Cron" >> /system/etc/cron.d/crontabs/root
    else
    echo "0 */$hour_opt * * * nohup /data/TrimDropOff/TrimDropOff_Cron" > /system/etc/cron.d/crontabs/root
    fi
    chmod 755 /system/etc/cron.d/crontabs/root;;
    d|D)echo "Input 0 to run at midnight every day,"
    echo "1 to run at 1:00 am...13 to run at 1:00 pm"
    echo -n "...etc...up to 23: "
    read daily_opt
    echo
    if [ ! "`echo $daily_opt | awk '!/[^0-9]/ && $1<=23'`" ]; then
    input_error
    fi
    if [ -f "/system/etc/cron.d/crontabs/root" ]; then
    echo "0 $daily_opt * * * nohup /data/TrimDropOff/TrimDropOff_Cron" >> /system/etc/cron.d/crontabs/root
    else
    echo "0 $daily_opt * * * nohup /data/TrimDropOff/TrimDropOff_Cron" > /system/etc/cron.d/crontabs/root
    fi
    chmod 755 /system/etc/cron.d/crontabs/root;;
    *)input_error;;
    esac;;
    n|N);;
    *)input_error;;
    esac

    cat > /system/xbin/trimdrop << EOF
    #!/system/bin/sh

    # This script was authored by Defiant07 @ xda. Feel free to use it as you see fit, but please give proper credits.
    # Read Karl Marx.

    clear

    trimmer(){
    echo "/system:"
    busybox sync
    fstrim -v /system
    echo "/data:"
    busybox sync
    fstrim -v /data
    echo "/cache:"
    busybox sync
    fstrim -v /cache
    }

    dropper(){
    echo "drop caches:"
    busybox sync
    busybox sysctl -w vm.drop_caches=3
    }

    echo -n "Do you want to run (f)strim, (d)rop_caches=3, or (b)oth? "
    read funct_opt
    echo
    case \$funct_opt in
    f|F)trimmer;;
    d|D)dropper;;
    b|B)trimmer
    dropper;;
    *)echo "That is not a valid input...try again...bye :p."
    exit 69;;
    esac
    echo
    echo "All done...enjoy! You can close your app now."

    exit 0
    EOF
    chmod 755 /system/xbin/trimdrop
    mount_ro

    echo "In addition to making the files required by"
    echo "your desired configuration, I have also made"
    echo "an on-the-fly script to run fstrim and/or"
    echo "drop_caches on-demand."
    echo "To use it, in terminal do: su -c trimdrop"
    echo
    sleep 3
    echo "Reboot your device to start your desired services."
    echo
    sleep 3
    echo "If you want to know how to verify everything"
    echo "is working, read the script's OP (FFS)!"
    echo
    sleep 5
    echo "All done...enjoy! You can close your app now."

    exit 0

    Changelog:
    v2.0
    • made in to installer script
    • added cron options
    • added bootloop precautions to the init.d scripts (should make it compatible with all devices that meet the requirments)
    • the on-the-fly script, trimdrop, now allows user to choose fstrim and/or drop_caches=3
    • added more syncs to further ensure no data is lost
    • a bunch of other stuff I probably forget
    v2.1
    • bug fixes - fixed issue if using only sync option (missing directory); fixed display of irrelevant errors in uninstall routine
    • cleaned code a bit (reduced redundancy)

    Download History:
    • Defiant07s_TrimDropOff.zip - [Click for QR Code] (1.6 KB, 162 views)
    • Defiant07s_TrimDropOff_v2.0_[NOT_FLASHABLE].zip - [Click for QR Code] (3.0 KB, 89 views)

    Credits:
    • Big thanks to @zeppelinrox, @dk_zero-cool, & @gu5t3r for their contributions to portions of this script (see the code of my other script SwapItOn for detailed citations).
    • Much thanks to @mdamaged for spotting the issue with sync init.d script and his note regarding syncing data.

    Don't forget to click THANKS and RATE 5 STARS if you found this useful :highfive:.

    peep my other script SwapItOn :p

    Update to v2.1 if you were only using the sync option.
    If you were using both the sync and schedule options or only the schedule option there is no need to update; the bug I found would not effect you.​
    5
    Released v2.0
    Fully Configurable Installer Script / Added Scheduling Options

    Important Note: If you were/are using the first version of this script, before installing v2.0 manually delete /etc/init.d/07TrimDropOff, /data/TrimDropOff_Awake.log, and /data/TrimDropOff_Sleep.log.

    Also Note: If you use crond for other tasks my script's install and uninstall routines account for this possibility and will leave your other crond tasks uneffected.


    changes:
    • made in to installer script
    • added cron options
    • added bootloop precautions to the init.d scripts (should make it compatible with all devices that meet the requirments)
    • the on-the-fly script, trimdrop, now allows user to choose fstrim and/or drop_caches=3
    • added more syncs to further ensure no data is lost
    • a bunch of other stuff I probably forget

    credits:
    • Big thanks to @zeppelinrox, @dk_zero-cool, & @gu5t3r for their contributions to portions of this script (see the code of my other script SwapItOn for detailed citations).
    • Much thanks to @mdamaged for spotting the issue with sync init.d script and his note regarding syncing data.

    I took a serious look in to making this an AROMA package, but due the nature of AROMA and all the options I would like to offer the user, it would be imho a roundabout coding process/a real pita. I still intend on taking on this challenge, but it will take longer than I thought; hence, this installer script to tide you kind folks over until I get around to solving the logical riddle that is AROMA.
    3
    Scheduling options would be awesome!


    Seems there is a decent amount of interest (almost 100 downloads already :)...thanks peeps), as such I'll add options and make things more configurable.

    Regarding scheduling, I was thinking of doing hourly, daily (with ability to choose time), and weekly (with ability to choose day and time) options. Would every other hour or some other setting be desirable?

    Regarding installation, what would be the preferred method, an installer script (e.g. V6 SuperCharger) or AROMA? Flashable zips would be another option, but would have less options/be less configurable.

    Gimme some feedback and I'll put something together in the next week or two depending on work and my motivation :p.
    3


    When I speak about priority, I do not speak about the importance of the scripts themselves, but rather the naming convention, lower numbers means higher priority, higher numbers are lower priority, so my wording was correct. In this case your script was higher priority(07 iirc) so it executed first, elementalx is lowest priority(99), but since the while loop is there it never got past 07 to get to 99.

    Did some googling and I stand corrected; you were/are completely correct. I my (messed-up) mind I always figured the higher the number the higher the priority because the last script that runs is the one whose settings stick. Imo, it seems counter-intuitive that a "higher priority" script could have it's settings superseded by a "lower priority" script.

    At any rate, I digress and thanks again for pointing out this issue and correcting my backwards thought :D.

    Made an installer script so everything is optional, plus I added cron options :)...gunna update OP now...
    3
    Thanks, sounds interesting. I'm assuming the zip can be flashed right after flashing a new rom? :)

    As you were informed the zip is NOT flashable. If there is sufficient interest (say a 100 downloads) I'll make it flashable/aroma.

    Is compatible with custom kernel? Franco in my case

    vía n7II r-paco

    Yes, it should be compatible...the fstrim utility is part of the rom (it should be in all nexus 4.3+ roms).

    Will performing trimming operations too frequently cause additional flash memory degradation?

    No, to my limited knowledge it should not be harmful (in fact it should increase lifespan - google "fstrim lifespan"). Did a quick google search but could not find anything definitive/reliable regarding frequency...what I did see seemed to suggest 'no' though.

    If you are concerned about the frequency, you could not install the init.d script and just use the on-the-fly script, trimdrop, to trim on-demand. Should there be interest and if I have the motivation and time, I have been thinking about making this in to an installer script and/or aroma zip with cron-based options so it could be scheduled hourly, daily, or weekly.