CentOS crontab timed task design

At the commandtaskisrunonlyonce,cyclingroutineplanningtasks,Linuxsystemsisby the cron(crond)tocontrolthissystemservice.Linux systemhas an awfullotofplanningwork,sothisserviceisstartedbydefault. In addition,userscanalsoset up a scheduledtask,soLinux systemalsoprovidesuserscheduledtaskscommand:crontabcommand.

A,crondprofile

Crond is Linux Xia used to periodic of implementation a species task or waiting for processing some event of a guardian process, and Windows Xia of plans task similar, dang installation completed operating system Hou, default will installation this service tool, and will automatically started crond process, crond process each minutes will regularly check whether has to implementation of task, if has to implementation of task, is automatically implementation the task.

Qian four line is used to configuration crond task run of environment variable, first line SHELL variable specified has system to using which shell, here is bash, second line PATH variable specified has system implementation command of path, third line MAILTO variable specified has crond of task implementation information will through e-mail sent to root user, if MAILTO variable of value for empty, is said not sent task implementation information to user, LastlinetheHOME variable to specifythecommandorscript to usehomedirectories.Sixthto Nineth line indicate in detailin the nextsection.Hereis notsaid.

Taskscheduling in user: the userof the workto beperformed on a regular basis,such asusers, such asdatabackup,scheduledemailalerts.Userscanusecrontabtocustomizetheir ownscheduledtasks.Alluser–definedcrontabfilesarestoredin the/var/spool/crondirectory.Itsfile nameandusername.

Userpermissionsfile:

File:

/etc/cron.deny

Introductions:

Theuserslistedin the filesdoes notallowusing the crontabcommand

File:

/etc/cron.allow

Introductions:

Theuserslistedin the filesusing the crontabcommand

File:

/var/spool/cron/

Introductions:

Alluserscrontabfilesstoredirectory,username

Meaningof the crontabfile:

Usercreatedthecrontabfile,eachrowrepresentsatask,eachrowofeachfieldrepresentsaset,itsformatis divided intosixfields, a formerfive–timesetting, the sixthisthecommandto beexecuted, in the followingformat:

minute hour day month week command

Of which:

Minute:forminutes, which canbeanyintegerfrom0to59.

Hour: the hour, which canbeanyintegerfrom0to23.

Day:date, which canbeanyintegerfrom1to31.

Month:month, which canbeanyintegerfrom1to12.

Week:that day of the week, which canbeanyintegerfrom0to7,where0or7forSunday.

Command:commandtoexecute, it maybe a systemcommand,or itcanbe to writeyour ownscriptfile.

Ineach of thesefields, you canalsouse the followingspecialcharacters:

An asterisk(*):representsallpossiblevalues,such asif the monthfieldisan asterisk,thenin the otherfieldconditionsevery monthafterthecommandoperation.

A comma(,):you canspecifyalist of valuesseparatedbycommas,for example,“1,2,5,7,8,9“

Forwardslash(/):canuseforwardslashes to specify the timeintervaloffrequencies,for example,“0-23/2“meansonceeverytwohours.Alsouseforwardslashandasterisk,for example,*/10,if you are usingin the minutefield,sayonceeverytenminutes.

Second,crondservice

Installcrontab:

yum install crontabs

Serviceinstructions:

/Sbin/serviceservicecrondstart//start

/Sbin/serviceservicecrondstop/on/off

/Sbin/servicerestartcrondrestart//services

/Sbin/servicecrondreload//reloadconfiguration

Seecrontabservicestatus:

service crond status

Crontabservicemanually:

service crond start

Seecrontabserviceisalreadysettoboot,execute the command:

ntsysv

AddedAutostart:

chkconfig –level 35 crond on

Third, the crontabcommandxiangjie

1.Commandformat:

crontab [-u user] file

crontab [-u user] [ -e | -l | -r ]

2.Commandfunction:

With the crontabcommand,wecan beperformedatregularintervals the specifiedsystemcommandorshellscriptscript.Intervalunitscanbeminutes,hours,days,months,weeks, andanycombinationof the above.Thiscommandisset upperiodicloganalysisordatabackups, and so on.

File:fileisthename of a commandfile,says it willfileforthetasklistandload the filecrontabcrontab.Ifthisfile is notspecifiedon the commandline,crontabcommandacceptsstandardinput(keyboard)you typeon the command,andloadthemintocrontab.

-E:Edit the contents of auser‘scrontabfile.If youdo notspecify a user,youedit the crontabfileof the currentuser.

-L:displays the contents of auser‘scrontabfile,if youdo notspecify a user,thendisplays the contents of currentuser‘scrontabfile.

Taking into accountbeforesubmittingacrontabfile for thecronprocess,firstthingtodois to set the environmentvariableEDITOR.Cronprocessaccording to itsedit the crontabfiletodeterminewhicheditor to use.99%useVIforUNIX andLINUX users,ifyou dotoo,thenyoueditunder your $HOME directory.Profilefile,adda linethat says:

EDITOR=vi; export EDITOR

Thensaveandexit.Might as wellcreatea<user>cronfile,which<user>is a username,such asdavecron.Add the followingcontentsinthefile.

# (put your own initials here)echo the date to the console every

# 15minutes between 6pm and 6am

0,15,30,45 18-06 * * * /bin/echo ‘date’ > /dev/console

To saveandexit.Surefront5fieldsseparatedby a space.

In the aboveexample, the systemwilloutputto the consoleevery1–5minutescurrenttime.If the systemcrashesorhangs,thetimecan bedisplayedfrom the last at aglanceis the systemstoppedworking.Insomesystems,by the tty1console,according to theaboveexampleismodifiedaccordingly.In order tosubmityourcrontabfile you justcreated,you canputthisnewlycreatedfileas a croncommandparameters:

Andyouwillseesomething similar to theabove.You canusethismethodin$homeabackuptocrontabfilesin a directory:

$ crontab -l > $HOME/mycron

That way,if you accidentallydeleted the crontabfile,you canusethemethodsdescribed in the previoussectionquicklyrestored.

3).editingcrontabfiles

If youwant to add,deleteoreditentriesincrontabfile,environmentvariable is settoedITO rvIvIcan beusedtoedit a crontabfile, the correspondingcommandis:

$ crontab -e

VIeditcan beusedlikeanyotherfilesthatmodify the crontabfileandexit.If you have modifiedsome of the entries, oraddanewentry,whenyousavethefile,cronbe the necessaryintegritychecks.Ifoneof these domainshavevalueoutside the allowedrange,itwillalertyou.

Whenweedit the crontabfile,maybe I‘lladd a newentry.For example,add the followingrule:

# DT:delete core files,at 3.30am on 1,7,14,21,26,26 days of each month

# DT:delete core files,at 3.30am on 1,7,14,21,26,26 days of each month

30 3 1,7,14,21,26 * * /bin/find -name “core’ -exec rm {} \;

4).removingcrontabfiles

Todelete a crontabfile,you canuse:

$ crontab -r

5.)recoverlostcrontabfiles

If youaccidentallydeleted the crontabfile,ifyouown$home–directoriesalsohaveabackup,youcancopyitto the/var/spool/cron/<username>,which<username>is the username.Ifdue to a permissionsproblemcannotcomplete the copy,you canuse:

$ crontab <filename>

Where<filename>isyour$home–copyof the filesin a directoryname.

Isuggestyouown$homesavingacopyofthefilein the directory.Ihad a similarexperience,mistakenlydeletedthecrontabfiles a number of times(close to the rightoftheerkey).Thisiswhysomesystemdocumentationrecommendsagainstdirectlyeditingcrontabfiles,buteditingacopyofthefile,and thenresubmit the newfile.

Crontabvariantsofsomespooky,sousecautionwhenusing the crontabcommand.If youmissedanyoptions,crontabmayopenanemptyfile,orlookslikeablankfile.ThenpressDELETEkey to exit,do notpress<Ctrl-D> oryouwilllose the crontabfile.

5.Useexamples

Example1:every1minutes to performacommand

Command:

* * * * * command

Example2:3rdperhourand15minutes

Command:

3,15 * * * * command

Example3:3rdat8o’clockin the morning to 11 pointsand15minutes

Command:

3,15 8-11 * * * command

Example4:everydayat 8 o’clock in the morning to11pointsin the 3rdand15minutes

Command:

3,15 8-11 */2 * * command

Example5:every3rdMondaymorning at 8 o’clock in the morning to11pointsand15minutes

Command:

3,15 8-11 * * 1 command

Example6:night 21:30 restart the SMB

Command:

30 21 * * * /etc/init.d/smb restart

Example7:1,10,22ndofeach month 4:45 restart the SMB

Command:

45 4 1,10,22 * * /etc/init.d/smb restart

Example8: every Saturday and Sunday 1:10 restart the SMB

Command:

10 1 * * 6,0 /etc/init.d/smb restart

Example9:dailyevery30minutesbetween 18:00 to 23:00 restart the SMB

Command:

0,30 18-23 * * * /etc/init.d/smb restart

Example10:11:00pmeverySaturdaynighttorestart the SMB

Command:

0 23 * * 6 /etc/init.d/smb restart

Example11:everyhourtorestart the SMB

Command:

* */1 * * * /etc/init.d/smb restart

Example12:11 o’clock in the eveninguntil7 in the morning,betweenevery two hourstorestart the SMB

Command:

* 23-7/1 * * * /etc/init.d/smb restart

Example13:the4th of each monthandeveryMondaytoWednesday11restartSMB

Command:

0 11 4 * mon-wed /etc/init.d/smb restart

Example14:January 1 4restartSMB

Command:

0 4 1 jan * /etc/init.d/smb restart

Example15:hourly/etc/cron.hourlydirectoryscript is executed

Command:

01 * * * * root run-parts /etc/cron.hourly

Introductions:

Thisparameter is run-parts,ifthisparameter is removed,youcanwriteascripttorunbehind,instead of the directoryname

Four,useprecautions

1.pay attention to environmentvariableproblem

Sometimeswecreateacrontab,butthistaskcannot beexecutedautomatically,andperformthistaskmanuallyisnoproblem,thissituationisusuallycauseddue to notconfigured the environmentvariablein the crontabfile.

In crontab file in the defined multiple scheduling task Shi, need special note of a problem is environment variable of set, because we manual implementation a task Shi, is in current shell environment Xia for of, program certainly can found environment variable, and system automatically implementation task scheduling Shi, is not loaded any environment variable of, so, on need in crontab file in the specified task run by needed of all environment variable, such, system implementation task scheduling Shi on no problem has.

Do notassume thatcronknowsthespecialcircumstancesrequired,itin factdoes notknow.Soyouneed tokeepin the shelllscriptprovidesallnecessarypathsandenvironmentvariables,except for someglobalvariable is automaticallyset.Sopay attention to the following3points:

3)whenmanuallyexecuting the scriptOK butcrontabdoes notexecute.Whenmustboldenvironmentvariableissuspected to blame,directlyinto the environmentvariablein the crontabandcantry to solve the problem.Such as:

Completion of eachtaskscheduling, the systemoutputsthetaskinformation is sentviae-mail to the currentusers of the system,so thatover time,loginformationwill beverylarge, and mayaffectthenormaloperation of the system and,therefore,toredirecteverytaskisimportant.

For example,you cansetin the crontabfileas follows,ignoring the logoutput:

0 */3 * * * /usr/local/apache2/apachectl restart >/dev/null 2>&1

“/Dev/null2>&1“toredirectstandardoutputto/dev/null,and thenredirectingstandarderrorintostandardoutput,standardoutputisredirectedto/dev/null,so the standarderrorwillberedirectedto/dev/null,so that the logoutputproblemissolved.

3.user-levelandsystem-leveltaskschedulingjobscheduling

System level task scheduling main completed system of some maintenance operation, user level task scheduling main completed user since defined of some task, can will user level task scheduling put to system level task scheduling to completed (not recommends so do), but in turn is no, root user of task scheduling operation can through “crontab – uroot – e” to set, also can will scheduling task directly writes/etc/crontab file, need note of is, Ifyou want todefineascheduledtask to restart the system,tasksmustbeplacedinto the/etc/crontabfile,evenunder the rootuser to createascheduledtask to restart the systemisinvalid.