Archive

Articles taggués ‘batch’

Cron Job Tutorial: Crontab Scheduling Syntax and Script Example

29/01/2024 Comments off

source: Devshed

Crontabs is very useful when doing website maintenance. You can use this feature for the following purposes:

  1. Deleting all files in a certain folder at regular intervals. If you accept user-uploaded files, then eventually it will clog your web hosting server. If you do not regularly delete these files, they will consume a lot of disk space and can slow down your website.
  2. Deleting files of a specific type at regular intervals. You can also choose to delete files of a specific type, instead of deleting all of the files in the folder. If you have PHP, HTML and MP3 files together inside the folder, you can delete only the MP3 files.
  3. Regularly backing up your MySQL database. This is one of the most important webmaster tasks. By using crontabs or the cron job feature, you can create a PHP script that will back up a selected MySQL database, and have it execute automatically executed at a specific, regular interval (e.g monthly, yearly, etc).

This tutorial will focus on creating a cron PHP script application, then configuring your cron hosting feature to execute these scripts automatically. Lire la suite…

Categories: Système Tags: , , ,

How to list the crontabs for all users?

09/01/2024 Comments off

I ended up writing a script (I’m trying to teach myself the finer points of bash scripting, so that’s why you don’t see something like Perl here). It’s not exactly a simple affair, but it does most of what I need. It uses Kyle’s suggestion for looking up individual users’ crontabs, but also deals with /etc/crontab(including the scripts launched by run-parts in /etc/cron.hourly/etc/cron.daily, etc.) and the jobs in the /etc/cron.d directory.source: How do I list all cron jobs for all users?

I ended up writing a script (I’m trying to teach myself the finer points of bash scripting, so that’s why you don’t see something like Perl here). It’s not exactly a simple affair, but it does most of what I need. It uses Kyle’s suggestion for looking up individual users’ crontabs, but also deals with /etc/crontab(including the scripts launched by run-parts in /etc/cron.hourly/etc/cron.daily, etc.) and the jobs in the /etc/cron.d directory.

It takes all of those and merges them into a display something like the following:

#!/bin/bash
# System-wide crontab file and cron job directory. Change these for your system.
 CRONTAB='/etc/crontab'
 CRONDIR='/etc/cron.d'
# Single tab character. Annoyingly necessary.
 tab=$(echo -en "\t")
# Given a stream of crontab lines, exclude non-cron job lines, replace
 # whitespace characters with a single space, and remove any spaces from the
 # beginning of each line.
 function clean_cron_lines() {
 while read line ; do
 echo "${line}" |
 egrep --invert-match '^($|\s*#|\s*[[:alnum:]_]+=)' |
 sed --regexp-extended "s/\s+/ /g" |
 sed --regexp-extended "s/^ //"
 done;
 }
# Given a stream of cleaned crontab lines, echo any that don't include the
 # run-parts command, and for those that do, show each job file in the run-parts
 # directory as if it were scheduled explicitly.
 function lookup_run_parts() {
 while read line ; do
 match=$(echo "${line}" | egrep -o 'run-parts (-{1,2}\S+ )*\S+')
if [[ -z "${match}" ]] ; then
 echo "${line}"
 else
 cron_fields=$(echo "${line}" | cut -f1-6 -d' ')
 cron_job_dir=$(echo "${match}" | awk '{print $NF}')
if [[ -d "${cron_job_dir}" ]] ; then
 for cron_job_file in "${cron_job_dir}"/* ; do # */
 [[ -f "${cron_job_file}" ]] && echo "${cron_fields} ${cron_job_file}"
 done
 fi
 fi
 done;
 }
# Temporary file for crontab lines.
 temp=$(mktemp) || exit 1
# Add all of the jobs from the system-wide crontab file.
 cat "${CRONTAB}" | clean_cron_lines | lookup_run_parts >"${temp}"
# Add all of the jobs from the system-wide cron directory.
 cat "${CRONDIR}"/* | clean_cron_lines >>"${temp}" # */
# Add each user's crontab (if it exists). Insert the user's name between the
 # five time fields and the command.
 while read user ; do
 crontab -l -u "${user}" 2>/dev/null |
 clean_cron_lines |
 sed --regexp-extended "s/^((\S+ +){5})(.+)$/\1${user} \3/" >>"${temp}"
done <
# Output the collected crontab lines. Replace the single spaces between the
 # fields with tab characters, sort the lines by hour and minute, insert the
 # header line, and format the results as a table.
 cat "${temp}" |
 sed --regexp-extended "s/^(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(.*)$/\1\t\2\t\3\t\4\t\5\t\6\t\7/" |
 sort --numeric-sort --field-separator="${tab}" --key=2,1 |
 sed "1i\mi\th\td\tm\tw\tuser\tcommand" |
 column -s"${tab}" -t
rm --force "${temp}"

source: How do I list all cron jobs for all users?

How to Run Cron Every 5 Minutes, Seconds, Hours, Days, Months

01/10/2023 Comments off

Source: thegeekstuff.com

Question: How do I execute certain shell script at a specific intervals in Linux using cron job? Provide examples using different time periods.

Answer: Crontab can be used to schedule a job that runs on certain internal. The example here show how to execute a backup.sh shell script using different intervals.

Also, don’t forget to read our previous crontab article that contains 15 practical examples, and also explains about @monthly, @daily, .. tags that you can use in your crontab.

1. Execute a cron job every 5 Minutes

The first field is for Minutes. If you specify * in this field, it runs every minutes. If you specify */5 in the 1st field, it runs every 5 minutes as shown below.

*/5 * * * * /home/ramesh/backup.sh

Note: In the same way, use */10 for every 10 minutes, */15 for every 15 minutes, */30 for every 30 minutes, etc.

2. Execute a cron job every 5 Hours

The second field is for hours. If you specify * in this field, it runs every hour. If you specify */5 in the 2nd field, it runs every 5 hours as shown below.

0 */5 * * * /home/ramesh/backup.sh

Note: In the same way, use */2 for every 2 hours, */3 for every 3 hours, */4 for every 4 hours, etc.

3. Execute a job every 5 Seconds

Cron job cannot be used to schedule a job in seconds interval. i.e You cannot schedule a cron job to run every 5 seconds. The alternative is to write a shell script that uses ‘sleep 5′ command in it.

Lire la suite…

Categories: Système Tags: , , ,

Un petit script de sauvegarde en shell pour vos machines Linux

23/05/2021 Comments off

On ne le répétera jamais assez : faites des sauvegardes ! Et non, ça n’est pas compliqué, oui il existe des dizaines et des dizaines de solutions possibles, donc vous n’avez pas d’excuse pour ne pas le faire.

disque-dur

Si vous utilisez WordPress, vous avez peut-être déjà installé l’extension BackWPUp qui fonctionne à merveille. Si ça n’est pas le cas, ou si vous souhaitez sauvegarder d’autres projets en même temps, je vous propose ce petit script de sauvegarde en shell (pour Ubuntu par exemple) qui vous permettra de :

  • sauvegarder tous les fichiers d’un répertoire ;
  • mettre à jour votre répertoire à partir d’un serveur distant ;
  • créer un dump de vos bases de données, une par une ;
  • mettre à jour vos bases de de données à partir d’un serveur distant ;
  • créer une archive gzippée de votre sauvegarde.

Et tout ça en moins de 50 lignes, commentaires compris.

Ainsi vous n’aurez qu’à planifier un lancement de ce script à la fréquence qui vous convient pour ne pas avoir à vous soucier de vos backups. Lire la suite…

Categories: Système, Tutoriel Tags: , , ,

Programmer l’heure d’exécution de Time Machine

28/01/2014 Comments off

Source: korben.info

u_04030644

Si vous êtes utilisateur d’OSX, peut-être faites-vous vos sauvegardes avec Time Machine sur un NAS ou une Time Capsule…

Et ça vous fait ch*er car cette sauvegarde se lance une fois par heure, faisant ramer votre ordinateur déjà un peu à bout de souffle… C’est quand même un peu sauvage un backup incrémental toutes les heures, surtout quand on passe sa vie sur The Pirate Bay 🙂

Alors, comment faire pour programmer cette sauvegarde une fois par jour (genre la nuit) ou une fois par semaine, voire une fois par mois si vraiment les sauvegarde vous n’en avez rien à faire (et ça c’est mal !) ?

La solution s’appelle Time Machine Editor. Il s’agit d’un petit soft pour OSX qui permet tout simplement de programmer le moment exact où vous souhaitez lancer la sauvegarde TimeMachine.

cap-2012-05-24-a-18.32.54

Attention, ce soft nécessite pour fonctionner efficacement, que vous désactiviez la TimeMachine. (oui, ça peut paraitre bizarre, mais Time Machine Editor gère son truc de son côté.)

cap-2012-05-24-a-18.44.08

Time Machine Editor est téléchargeable ici.

Edit: l’ami Daniel me recommande aussi TimeMachineScheduler qui fait sensiblement la même chose. Ce dernier ne nécessite pas de devoir désactiver la Time Machine et s’intègre dans les préférences système de l’OS.