CronHowto

Embed Size (px)

Citation preview

  • 7/30/2019 CronHowto

    1/9

    CronHowto

    Daftar Isi

    1. Introduction

    1. Using Cron

    2. Crontab Sections

    3. Crontab Options

    4. Enable User Level Cron

    5. Further Considerations

    6. Troubleshooting andCommon Problems

    7. Advanced Crontab

    8. GUI Applications

    2. Tips

    1. Crontab Example

    2. How Anacron is Arranged

    3. Cron Jobs Alternatives

    Introduction

    Cron is a system daemon used to execute desired tasks (in the background) at designatedtimes.

    A crontab is a simple text file with a list of commands meant to be run at specified times. It isedited with a command-line utility. These commands (and their run times) are then controlled

    by the cron daemon, which executes them in the system background. Each user has a crontabfile which specifies the actions and times at which they should be executed, these jobs will

    run regardless of whether the user is actually logged into the system. There is also a rootcrontab for tasks requiring administrative privileges. This system crontab allows schedulingof systemwide tasks (such as log rotations and system database updates).

    More information can be found:

    man crontab

    or from the OpenGroup specifications.

    An alternative in Gnome-based Ubuntu systems is to use the Gnome Scheduled tasks tool

    (from thegnome-schedule package) inApplications --> System Tools.

    https://help.ubuntu.com/community/CronHowto?action=fullsearch&context=180&value=linkto%3A%22CronHowto%22https://help.ubuntu.com/community/CronHowto#Introductionhttps://help.ubuntu.com/community/CronHowto#Using_Cronhttps://help.ubuntu.com/community/CronHowto#Crontab_Sectionshttps://help.ubuntu.com/community/CronHowto#Crontab_Optionshttps://help.ubuntu.com/community/CronHowto#Enable_User_Level_Cronhttps://help.ubuntu.com/community/CronHowto#Further_Considerationshttps://help.ubuntu.com/community/CronHowto#Troubleshooting_and_Common_Problemshttps://help.ubuntu.com/community/CronHowto#Troubleshooting_and_Common_Problemshttps://help.ubuntu.com/community/CronHowto#Advanced_Crontabhttps://help.ubuntu.com/community/CronHowto#GUI_Applicationshttps://help.ubuntu.com/community/CronHowto#Tipshttps://help.ubuntu.com/community/CronHowto#Crontab_Examplehttps://help.ubuntu.com/community/CronHowto#How_Anacron_is_Arrangedhttps://help.ubuntu.com/community/CronHowto#Cron_Jobs_Alternativeshttp://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.htmlhttps://help.ubuntu.com/community/CronHowto#Introductionhttps://help.ubuntu.com/community/CronHowto#Using_Cronhttps://help.ubuntu.com/community/CronHowto#Crontab_Sectionshttps://help.ubuntu.com/community/CronHowto#Crontab_Optionshttps://help.ubuntu.com/community/CronHowto#Enable_User_Level_Cronhttps://help.ubuntu.com/community/CronHowto#Further_Considerationshttps://help.ubuntu.com/community/CronHowto#Troubleshooting_and_Common_Problemshttps://help.ubuntu.com/community/CronHowto#Troubleshooting_and_Common_Problemshttps://help.ubuntu.com/community/CronHowto#Advanced_Crontabhttps://help.ubuntu.com/community/CronHowto#GUI_Applicationshttps://help.ubuntu.com/community/CronHowto#Tipshttps://help.ubuntu.com/community/CronHowto#Crontab_Examplehttps://help.ubuntu.com/community/CronHowto#How_Anacron_is_Arrangedhttps://help.ubuntu.com/community/CronHowto#Cron_Jobs_Alternativeshttp://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.htmlhttps://help.ubuntu.com/community/CronHowto?action=fullsearch&context=180&value=linkto%3A%22CronHowto%22
  • 7/30/2019 CronHowto

    2/9

    Using Cron

    To use cron for tasks meant to run only for your user profile, add entries to your own user'scrontab file. Start the crontab editor from a terminal window:

    crontab -e

    Edit the crontab using the format described in the next sections. Save your changes. (Exitingwithout saving will leave your crontab unchanged.)

    Note that a great source of information about the format can be found at:

    man 5 crontab

    Commands that normally run with administrative privileges (i.e. they are generally run usingsudo) should be added to the root user's crontab (instead of the user's crontab):

    sudo crontab -e

    Crontab Sections

    Each of the sections is separated by a space, with the final section having one or more spacesin it. No spaces are allowed within Sections 1-5, only between them. Sections 1-5 are used toindicate when and how often you want the task to be executed. This is how a cron job is laidout:

    minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 =Sunday), command

    01 04 1 1 1 /usr/bin/somedirectory/somecommand

    The above example will run /usr/bin/somedirectory/somecommand at 4:01am on January 1stplus every Monday in January. An asterisk (*) can be used so that every instance (every hour,every weekday, every month, etc.) of a time period is used. Code:

    01 04 * * * /usr/bin/somedirectory/somecommand

    The above example will run /usr/bin/somedirectory/somecommand at 4:01am on every day ofevery month.

    Comma-separated values can be used to run more than one instance of a particular commandwithin a time period. Dash-separated values can be used to run a command continuously.Code:

    01,31 04,05 1-15 1,6 * /usr/bin/somedirectory/somecommand

    The above example will run /usr/bin/somedirectory/somecommand at 01 and 31 past thehours of 4:00am and 5:00am on the 1st through the 15th of every January and June.

  • 7/30/2019 CronHowto

    3/9

    The "/usr/bin/somedirectory/somecommand" text in the above examples indicates the taskwhich will be run at the specified times. It is recommended that you use the full path to thedesired commands as shown in the above examples. Enterwhich somecommandin theterminal to find the full path tosomecommand. The crontab will begin running as soon as it is

    properly edited and saved.

    You may want to run a script some number of times per time unit. For example if you want torun it every 10 minutes use the following crontab entry (runs on minutes divisible by 10: 0,10, 20, 30, etc.)

    */10 * * * * /usr/bin/somedirectory/somecommand

    which is also equivalent to the more cumbersome

    0,10,20,30,40,50 * * * * /usr/bin/somedirectory/somecommand

    Crontab Options

    The -l option causes the current crontab to be displayed on standard output.

    The -r option causes the current crontab to be removed.

    The -e option is used to edit the current crontab using the editor specified by the

    EDITOR environment variable.

    After you exit from the editor, the modified crontab will be checked for accuracy and, if thereare no errors, installed automatically. The file is stored in/var/spool/cron/crontabs but shouldonly be edited via the crontab command.

    Enable User Level Cron

    If the /etc/cron.allow file exists, then users must be listed in it in order to be allowed to runthe crontab command. If the /etc/cron.allow file does not exist but the /etc/cron.deny filedoes, then users must not be listed in the /etc/cron.deny file in order to run crontab.

    In the case where neither file exists, the default on current Ubuntu (and Debian, but not someother Linux and UNIX systems) is to allow all users to run jobs with crontab.

    No cron.allow or cron.deny files exist in a standard Ubuntu install, so all users should havecron available by default, until one of those files is created. If a blank cron.deny file has beencreated, that will change to the standard behavior users of other operating systems mightexpect: cron only available to root or users in cron.allow.

    Note, userids on your system which do not appear in /etc/shadow will NOT have operationalcrontabs, if you desire to enter a user in /etc/passwd, but NOT /etc/shadow that user's crontabwill never run. Place an entry in /etc/shadow for the user with a * for the password crypt,ie:

    joeuser:*:15169::::::

    Further Considerations

  • 7/30/2019 CronHowto

    4/9

    Crontab commands are generally stored in the crontab file belonging to your user account(and executed with your user's level of permissions). If you want to regularly run a commandrequiring administrative permissions, edit the root crontab file:

    sudo crontab -e

    Depending on the commands being run, you may need to expand the root users PATHvariable by putting the following line at the top of their crontab file:

    PATH=/usr/sbin:/usr/bin:/sbin:/bin

    It is sensible to test that your cron jobs work as intended. One method for doing this is to setup the job to run a couple of minutes in the future and then check the results before finalisingthe timing. You may also find it useful to put the commands into script files that log theirsuccess or failure, for example:

    echo "Nightly Backup Successful: $(date)" >> /tmp/mybackup.log

    For more information, see the man pages forcron and crontab (man is detailed on theBasicCommandspage). If your machine is regularly switched off, you may also be interestedin at and anacron, which provide other approaches to scheduled tasks. For example,anacron offers simple system-wide directories for running commands hourly, daily, weekly,and monthly. Scripts to be executed in said times can be placed in /etc/cron.hourly/,/etc/cron.daily/, /etc/cron.weekly/, and /etc/cron.monthly/. All scripts in each directory arerun as root, and a specific order to running the scripts can be specified by prefixing thescripts' filenames with numbers (see the man page forrun-parts for more details). Althoughthe directories contain periods in their names, run-parts will not accept a file name containing

    a period and will fail silently when encountering them (bug #38022). Either rename the file oruse a symlink (without a period) to it instead (see, for example,python + cron without login?andProblems with Hourly Cron Job).

    Troubleshooting and Common Problems

    Edits to a user's crontab and jobs that are run on their behalf are all logged by default to/var/log/syslog and that's the first place to check if things are not running as you expect.

    When adding a new entry to a blank crontab, forgetting to add a newline at the end is a

    common source for the job not running. If the last line in the crontab does not end with anewline, no errors will be reported at edit or runtime, but that line will never run. See mancrontab for more information. This has already been suggested as a bug.

    If a user was not allowed to execute jobs when their crontab was last edited, just adding themto the allow list won't do anything. The user needs to re-edit their crontab after being added tocron.allow before their jobs will run.

    When creating a crontab for the root user, the user name must be specified as a parameterafter the date/time parameters. Accidentally including the user name that way in a user-specific crontab will result in trying to run the user's name as a command, rather than what

    was expected.

    https://help.ubuntu.com/community/BasicCommandshttps://help.ubuntu.com/community/BasicCommandshttps://bugs.launchpad.net/ubuntu/+source/debianutils/+bug/38022http://ubuntuforums.org/showthread.php?t=1629301http://ubuntuforums.org/showthread.php?t=1629301http://ubuntuforums.org/showthread.php?t=1692253https://bugs.launchpad.net/ubuntu/+source/cron/+bug/118168https://bugs.launchpad.net/ubuntu/+source/cron/+bug/118168https://help.ubuntu.com/community/BasicCommandshttps://bugs.launchpad.net/ubuntu/+source/debianutils/+bug/38022http://ubuntuforums.org/showthread.php?t=1629301http://ubuntuforums.org/showthread.php?t=1692253https://bugs.launchpad.net/ubuntu/+source/cron/+bug/118168
  • 7/30/2019 CronHowto

    5/9

    Entries in cron may not run with the same environment, in particular the PATH, as youexpect them to. Try using full paths to files and programs if they're not being located as youexpect.

    The "%" character is used as newline delimiter in cron commands. If you need to pass that

    character into a script, you need to escape it as "\%".

    If you're having trouble running a GUI application using cron, see the GUI Applicationssection below.

    Advanced Crontab

    The Crontabs discussed above are user crontabs. Each of the above crontabs is associatedwith a user, even the system crontab which is associated with the root user. There are twoother types of crontab.

    Firstly, as mentioned above anacron uses the run-parts command and /etc/cron.hourly,/etc/cron.weekly, and /etc/cron.monthly directories. Howeveranacron itself is invokedfrom the /etc/crontab file. This file could be used for other cron commands, but probablyshouldn't be. Here's an example line from a ficticious /etc/crontab:

    00 01 * * * rusty /home/rusty/rusty-list-files.sh

    This would run Rusty's command script as userrusty from his home directory. However, it isnot usual to add commands to this file. While an experienced user should know about it, it isnot recommended that you add anything to /etc/crontab. Apart from anything else, this could

    cause problem if the /etc/crontab file is affected by updates! Rusty could lose his command.

    The second type of crontab is to be found in /etc/cron.d. Within the directory are smallnamed crontabs. The directory is often used by packages, and the small crontabs allows auser to be associated with the commands in them.

    Instead of adding a line to /etc/crontab which Rusty knows is not a good idea, Rusty mightwell add a file to /etc/cron.d with the name rusty, containing his cron line above. This wouldnot be affected by updates but is a well known location.

    When would you use these alternate crontab locations? Well, on a single user machine or a

    shared machine such as a school or college server, a user crontab would be the way to go.But in a large IT department, where several people might look after a server, then /etc/cron.dis probably the best place to install crontabs - it's a central point and saves searching forthem!

    You may not need to look at /etc/crontab or/etc/cron.d, let alone edit them by hand. But anexperienced user should perhaps know about them and that the packages that he/she installsmay use these locations for their crontabs.

    Special strings

    Cron also offers some special strings:

  • 7/30/2019 CronHowto

    6/9

    string meaning

    @reboot Run once, at startup.

    @yearly Run once a year, "0 0 1 1 *".

    @annually (same as @yearly)

    @monthly Run once a month, "0 0 1 * *".

    @weekly Run once a week, "0 0 * * 0".

    @daily Run once a day, "0 0 * * *".

    @midnight (same as @daily)

    @hourly Run once an hour, "0 * * * *".

    Usage: "@reboot /path/to/execuable1" will execute /path/to/executable1 when the systemstarts. See "man 5 crontab" for more info.

    GUI Applications

    It is possible to run gui applications via cronjobs. This can be done by telling cron whichdisplay to use.

    00 06 * * * env DISPLAY=:0 gui_appname

    The env DISPLAY=:0 portion will tell cron to use the current display (desktop) for theprogram "gui_appname".

    And if you have multiple monitors, don't forget to specify on which one the program is to berun. For example, to run it on the first screen (default screen) use :

    00 06 * * * env DISPLAY=:0.0 gui_appname

    The env DISPLAY=:0.0 portion will tell cron to use the first screen of the current display forthe program "gui_appname".

    Note: GUI users may prefer to use gnome-schedule (aka "Scheduled tasks") to configureGUI cron jobs. In gnome-schedule, when editing a GUI task, you have to select "Xapplication" in a dropdown next to the command field.

    Note: In Karmic(9.10), you have to enable X ACL for localhost to connect to for GUIapplications to work.

    ~$ xhost +local:non-network local connections being added to access control list~$ xhostaccess control enabled, only authorized clients can connectLOCAL:...

    Tips

  • 7/30/2019 CronHowto

    7/9

    crontab -e uses the EDITOR environment variable. to change the editor to your own choicejust set that. You may want to set EDITOR in you .bashrc because many commands use thisvariable. Let's set the EDITOR to nano a very easy editor to use:

    export EDITOR=nano

    There are also files you can edit for system-wide cron jobs. The most common file is locatedat /etc/crontab, and this file follows a slightly different syntax than a normal crontab file.Since it is the base crontab that applies system-wide, you need to specify what user to run the

    job as; thus, the syntax is now:

    minute(s) hour(s) day(s)_of_month month(s) day(s)_of_week user command

    It is recommended, however, that you try to avoid using /etc/crontab unless you need theflexibility offered by it, or if you'd like to create your own simplified anacron-like systemusing run-parts for example. For all cron jobs that you want to have run under your own user

    account, you should stick with using crontab -e to edit your local cron jobs rather thaneditting the system-wide /etc/crontab.

    Crontab Example

    Below is an example of how to setup a crontab to run updatedb, which updates the slocatedatabase: Open a term, type "crontab -e" (without the double quotes) and press enter. Typethe following line, substituting the full path of the application you wish to run for the oneshown below, into the editor:

    45 04 * * * /usr/bin/updatedb

    Save your changes and exit the editor.

    Crontab will let you know if you made any mistakes. The crontab will be installed and beginrunning if there are no errors. That's it. You now have a cronjob setup to run updatedb, whichupdates the slocate database, every morning at 4:45.

    Note: The double-ampersand (&&) can also be used in the "command" section to runmultiple commands consecutively, but only if the previous command exits successfully. Astring of commands joined by the double-ampersand will only get to the last command if all

    the previous commands are run successfully. If exit error-checking is not of a concern, stringcommands together, separated with a semi-colon (;)

    45 04 * * * /usr/sbin/chkrootkit && /usr/bin/updatedb

    The above example will run chkrootkit followed by updatedb at 4:45am daily - providing youhave all listed apps installed. If chkrootkit fails, updatedb will NOT be run.

    How Anacron is Arranged

    On Ubuntu 9.10 (and presumably, on later versions), anacron seems to be set up as follows:

  • 7/30/2019 CronHowto

    8/9

    There is a Upstart task, located in /etc/init/anacron.conf, which runs all the jobs in/etc/anacrontab. It is set to run on startup.

    There is a cron.d file (/etc/cron.d/anacron) which causes the Upstart task to be started everyday at 7:30 AM.

    There is a file /etc/apm/event.d/anacron, which causes the Upstart task to be started when alaptop is plugged in to A/C power, or woken up.

    In the system crontab (/etc/crontab), if anacron is not execuatable, run-parts is used to runthe files in cron.daily, cron.weekly, and cron.monthly at 6:25 AM, 6:47 AM and 6:52 AM,respectively.

    In /etc/anacrontab , run-parts is used to run cron.daily 5 minutes after anacron is started, andcron.weekly after 10 minutes (once a week), and cron.monthly after 15 (once a month).

    Within the cron.daily, weekly, and monthly directories ( /etc/cron.daily, etc.) there is a0anacron file that sets the timestamps for anacron, so it will know they have been run, evenif it didn't run them.

    So it appears anacron is run on every startup, wake up, plug-in, and at 7:30 AM every day.Looking at the respective Changelogs and package databases, it looks like this setup isdirectly from Debian, and hasn't been changed since at least 2009.

    Cron Jobs Alternatives

    Some hosting companies dont allow access to cron, but you can find a lot of cron jobsalternatives which are free or paid.

    Here are some services:

    SetCronJob

    OnlineCronJobs

    CronJobs.org

    CronHowto (terakhir disunting 2011-09-14 03:32:35 oleh morrowc)

    Page History

    The material on this wiki is available under a free license, see Copyright / Licensefor detailsYou can contribute to this wiki, see Wiki Guidefor details

    Autobackups mysql ubuntu

    Instalasi AutoMySQLBackup:Instalasinya mudah hanya mengedit beberapa variabel di script AutoMySQLBackup tersebut.

    http://www.setcronjob.com/http://www.onlinecronjobs.com/http://www.cronjobs.org/https://launchpad.net/~morrowchttps://help.ubuntu.com/community/CronHowto?action=infohttps://help.ubuntu.com/community/Licensehttps://help.ubuntu.com/community/Licensehttps://help.ubuntu.com/community/WikiGuidehttps://help.ubuntu.com/community/WikiGuidehttp://www.setcronjob.com/http://www.onlinecronjobs.com/http://www.cronjobs.org/https://launchpad.net/~morrowchttps://help.ubuntu.com/community/CronHowto?action=infohttps://help.ubuntu.com/community/Licensehttps://help.ubuntu.com/community/WikiGuide
  • 7/30/2019 CronHowto

    9/9

    Dan dokumentasi nya juga ada di script shell tersebut.Ini contoh minimumu setup nya, langkah demi langkah 1. Download automysqlbackup.sh dihttp://sourceforge.net/projects/automysqlbackup/files/AutoMySQLBackup/ dan taruh didirektori /etc/cron.daily atau di home direktori Anda.

    2. Lakukan Edit dengan data Anda beberapa settingan berikut

    # Username to access the MySQL server e.g. dbuserUSERNAME=root# Username to access the MySQL server e.g. passwordPASSWORD=password untuk root# Host name (or IP address) of MySQL server e.g localhostDBHOST=localhost# List of DBNAMES for Daily/Weekly Backup e.g. DB1 DB2 DB3DBNAMES=test1 test2

    # Backup directory location e.g /backups

    BACKUPDIR="/home/server/backups"

    3. Rubah permissionnya file tsb dengan perintah : chmod u+rwx namafileshellnya4. Buat direktori berikut ./backups5. Selanjutnya membuat cron di ServerLihat waktu saat ini biar hasil cron nya bisa segera kita lihat berhasil apa tidakserver@server:/opt$ dateMon May 9 09:02:04 WIT 2011server@server:~$ sudo crontab -eSelect an editor. To change later, run 'select-editor'.1. /bin/ed2. /bin/nano