Linux/Mac Tutorial: Cron Jobs - How to Schedule Commands with crontab
18:50

Linux/Mac Tutorial: Cron Jobs - How to Schedule Commands with crontab

Corey Schafer 23.08.2017 259 840 просмотров 6 442 лайков

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI
Описание видео
In this Linux/Mac terminal tutorial, we will be learning about cron jobs and how to schedule commands with crontab. The will allow you to run commands on a repetitive schedule. So if you want to run a job daily, weekly, or at a certain time of day, this video will show you how you can get this set up. This helps a ton with system administration type of tasks and can automate a lot of work. Let's get started. The snippets from this video can be found at: https://github.com/CoreyMSchafer/code_snippets/tree/master/Cron-Tasks ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Linux #Mac

Оглавление (14 сегментов)

Intro

hey there how's it going everybody in this video we're going to be learning how to schedule tasks using the cron utility now you can use cron for pretty much anything but you see it used a lot to handle things like automated backups rotating log files syncing files between remote machines or clearing out temporary folders and things like that now just about anyone can find a lot of uses for cron tasks but it becomes especially useful once you start doing a system administration type of work so let's see how we can set this up now we can schedule the list of commands that we want to run using something called the cron table and the command is cron tab for short so first we can see a list of the current users cron jobs with the command cron tab - L so we can see that we don't have any scheduled jobs yet for this user so let's go ahead and add some now when we edit our crontab we're going to have to use an editor so for most operating systems this is going to default to them and that's what I'm going to be using for this video but if you aren't comfortable using them and would like to use something like Nano instead then you can set this environment variable called editor and you can set that to none Nano so we could say something like export editor and I believe that Nano is in user bin Nano so if you set that value then when you edit your contact in stead of them and also I think if you're on a boon - then it'll ask you to select your editor when you first try to edit your cron time but like I said I'm just going to keep the default of them for this video okay so let's go ahead and edit our crontab so we can edit our list of cron jobs by saying cron tab - E and if we

Simple commands

run that then it opens up our editor and in them if we want to insert something you can press I to put yourself in insert mode and it says insert down here at the bottom so we're just going to start off with some simple commands just to see how this works and then we'll look at some more practical examples once we get the hang of it so on each line we're going to specify when we're going to run our command and also the command that we want to run so let me grab a comment from my snippets here that will make this a little more clear so I'm going to copy these and paste them in here and then minimize that again okay so each line is going to look like this right here we're going to have five values that specify when we want the job to run and then the job that we want to execute now first we specify the minute and then the hour and then the day of the month week now we can use exact values or we can use an asterisk to match every value so for example one of the simplest schedules would be an asterisk for all five values so if I go ahead and type out a line here and I'm putting spaces between each of these so we have asterisks for all five of our values and then the command that we want to run and we'll just make this simple I'm just going to echo out hello and we want to put this into a temporary file so I'll send this to the temporary folder and to a file just called text txt and to save this in them we can press escape and then a colon W and I'll also quit out of here for now with the queue so now that we're back to our menu here let's list out our crontab to see to make sure that was safe successfully okay and now we can see our command that we added here so let's go over exactly what this is saying so is that we want to run this echo command and send it to that file we want to run that on every minute of every hour of every day of the week or month on every month on any day of the week now I know that sounds confusing but we're going to see a lot of examples and we'll get the hang of it after a while but basically what that says is that we're just going to run this command every minute of every day so there's a good chance that cron has already run this echo command and appended the word hello to our test txt file in the temp folder so let's go ahead and cat that file to see if that has run already so we can see that our command was successfully scheduled and run through our cron system okay now let's look at some different combinations for or how the schedule when our job is going to be run so to do this let's go back and edit our cron job again okay so

Edit cron job

the asterisk will match any value but we can also use exact values so the minutes can be anything between 0 & 59 so if I was to set this minute here to 30 then what this would mean is that our command would be run on the 30th minute of every hour of every day of the month on every month on any day of the week so if I look at what my local time is now it's about 10:40 so that means that this job would now get run 30 past the hour for every hour so this would run since it's 10:40 now this would run at 11:30 and then 12:30 and then 1:30 and 2:30 and so on now the hour can be anything between 0 & 23 so 0 for midnight and 23 for 11:00 p. m. at night so if we were to change this to a 5 so now this line is saying that we're going to run our command 30 minutes past the 5th hour on every single day so at 5:30 every single day it will run that command and we can continue just going down the line of values here so the days of the month can be anything between 1 and 31 so if we were to set the day of the month to 1 now what our line is saying is that

Day of the month

we're going to run our command 30 minutes past 5:00 on the 1st of every month so basically at 5:30 a. m. it will run our command so basically now our command is only going to run once a month and just like you might expect the months can be anything between 1 and 12 and if we were to set this to you know something like a value of 1 as well then now we're scheduling our command to run once a year so it would run at 5:30 a. m. on the 1st of the month of the first month which is January now this last value is for day of the week and this is really useful because sometimes we want to schedule commands to on at a certain time on a specific day and we can see our comment above that zero is Sunday and six is Saturday so let's say that I wanted to back up some files at midnight every Monday so to do this we could just set our day of the week to one which is Monday and then we want to put an asterisk for the month and then a day of the month and then a zero for the hour because we want it to be midnight and zero for the minute as well so just go over that one more time we have zero for our minute and zero for our hour which is midnight a combination of two zeros here's midnight and then for any day of the month for any month and then on the day of the week we want one which is Monday so every Monday at midnight run this command ok so now let's look at

Multiple values

some more advanced schedules so we can create a lot of different schedules with what we've learned so far but what if we had a script that we wanted to run on the 1st and 15th of every month now to do this we can use a comma operator to specify multiple values so for example let's say that we wanted to run a command at midnight on the 1st and the 15th of every month so we've already seen that a 0 for the minutes and hour is midnight and now we want it to run on the first day and the 15th day of the month so we can use a comma operator to do multiple values here so I can put in a 1 comma 15 and then we want an asterisk for any month and then day of the week so again that's a 0 for the minutes 0 for the hours which is midnight and then for the day of the month 1 comma 15 which means it will run on both the 1st and the 15th of every month now one common

Setting a specific time

mistake that people make when they schedule cron tasks is that it's important that we put a specific time like we did here like with midnight when we want to run something on a certain day like this because some people make the mistake of leaving these as asterisks here and they think that this will run on this command on the 1st and the 15th of every month as well but what this actually does is that it will run your command every minute of the day on the 1st and the 15th so it'll never run your command whenever it's not the first or the 15th of the month but whenever it is the first or it is the 15th then it's going to run our command every minute of that day and that's likely not what we wanted so to run it once that day then we have to select a specific time which in this case we're choosing midnight but you can choose whatever you like ok so now let's look at how we can schedule intervals so what if we wanted to run a command every 10 minutes then you could use multiple values here and say you know 0 10 20 30 and so on but that's pretty ugly and it

Setting an interval

also becomes completely unmanageable if we wanted to run you know something every two minutes or something like that so instead we can use the forward slash operator to do an interval so to run something every 10 minutes we could just put in an asterisk here and then a forged slash pin and then for these other values I'm just going to go ahead and fill in all asterisks for those so we have an asterisk here for our minute and then that forged slash 10 which actually says we just want to run this every 10 minutes and then asterisk for every other value which just means every 10 minutes of every day so then if you wanted to change that to run something every 5 minutes of every day then you could just change that 10 to a 5 and you're good to go and this works with the other values as well so let's say that you wanted to run a command every 3 days then we could put a 0 for the minutes hours and then for the days just a ford slash 3 and again that common mistake that I mentioned earlier if you want to run something every few hours or every few days then you have to be sure that you set the minutes and the hours to zero because if you made the mistake of leaving these as asterisks then it would just run every minute on every third day instead of once every three days so you have to be careful with that okay so lastly let's

Setting a range

look at ranges so let's say that we wanted to run a command every hour from midnight to 5:00 a. m. so to do this we can use the - operator to specify a range so I'm just going to use an asterisk for the day here for the minute I will keep at zero and let's say that we wanted to run a command every hour from midnight to 5:00 a. m. so we can keep this as zero then put in a dash 5 so the schedule that we currently have here would run this echo command every hour between 0 to 5 of every day so

Example schedule

another example might be you know something that you might want to schedule seasonally so let's say that you worked for a university and you had certain scripts that you wanted to run at noon every day during the summer months while the students were on break or something then you know you could write something like you know I want to run this at noon every day of the month but only through the months you know 5:00 to 8:00 which i think is made august ok so now let's do one more

Advanced example

advanced example that ties a few of these things together so let's say that we wanted to run a command every 30 minutes during regular business hours and common business hours are Monday through Friday from 9:00 a. m. to 5:00 p. m. so let's write this out so we want to run every 30 minutes Monday through Friday from 9:00 a. m. to 5:00 p. m. okay so I'm just going to make these all asterisks for now and then we will change these as we go ok so first we want to run a command every 30 minutes so we can use our interval and do every 30 minutes and now we want our hours to be between 9 a. m. and 5 p. m. so that would be 9 a. m. and then 5 p. m. and military time is just 17 and we also only want this command to run between Monday and Friday so we go here to the days of the week and we would do 1 which is Monday through 5 which is Friday so that's a little more complicated of a command but you these contests are really versatile and allow you to create you know some complicated schedules okay so hopefully

Multiple cron jobs

at this point you have a pretty good idea for how the schedule jobs to run on just about any schedule or integral that you would like now as one last example let me grab a couple of cron jobs from my snippets file here and they can just give some ideas for what multiple cron jobs might look like so I'll just grab a couple of these out of here and paste these in then minimize that okay so one

Comments

thing about editing your crontab is not to be shy about writing comments so I usually leave this entire timing comment here at the top micron tab but just as a reference in case I forget what one of these values are and then I also comment each cron task so for our first job here this is to remove the contents of our temp folder at 5:00 p. m. on every Friday so you can see we have a 0 for the minute 5 for the hour so that's actually 5 am sorry and then a 5 for the day of the week which is Friday and then our command will remove all the contents from our temp folder and the second task that I have here is to backup my pictures folder to Google Drive every night at midnight so these are just two small examples for how you can use what we learned here but I'm sure you'll be able to find plenty of use cases yourself but you can use these for you know system updates and all kinds of different things ok so real quick before we finish up here let me give a couple more tips for using cron so in this video we've been

Additional Tips

editing our own users cron tasks but if we ever wanted to view or edit another user's cron tasks then we can use the - you option to specify which user so for example we could say crontab - you and you know user - e now this would edit user twos cron tasks instead of your own cron tests now if you have any tasks that need to be run as a root user then we can just put sudo before the crontab so for example to view the roots cron tasks we could say to do crontab - L and that's going to ask for the sudo password and we can put that in and you can see that I currently don't have a cron tab for the root account but that is how you would edit the root or view the roots cron tabs so for example to edit the root crontab you would just do a dash e and then you're editing the root users contacts now another useful command is being able to easily remove cron tasks so you know if you've been playing around with your cron test while watching this video and would like to remove all of them then you can do that either by you know deleting all of the contents and the file that you just edited or you could just simply say crime tab - R - remove and if we run that and now we do a crontab - L you can see that now it says that we have no crontab for our user even though we saved everything that we were working with before okay so there's

Crontab Guru

one last thing that I'd like to show you so I know that those schedules can be a little difficult to comprehend especially you know in such a short video but if you're still unsure how those schedules work then there are some great tools online where you can type in a schedule and it will do its best to translate that schedule for you so one of the first results online is this crontab guru and in here we can add a schedule and it will do its best to tell us what that schedule is so for example we have five for the minute and four for the hour so it's saying that it'll run at 4:05 and another cool thing here is that the text is kind of small here I'm not sure if you can see in the video but it also shows an example of when at the next time this schedule would be executed based on the current time and if you click this next value here and it expands this out to show you the next five executions so what this is saying here is that this is going to execute at 4:05 a. m. on the next five days now if we were to change this to something like 0 for the minute 0 for the hour and then 1 for the day of the week and now we can see that this is saying that it's going to be on midnight on Monday and our schedule here is saying that it'll be on night on the seventh and then the 14th and then the 21st which I'm assuming are Mondays so even if you're pretty comfortable with how the scheduling works you know using sites like this can give you some reassurance that you're putting in the right values and that you're scheduling your jobs exactly how you expect okay so I think that is going to do it for this video I hope now that everybody has a good understanding for how scheduling tasks through cron works but if anyone does have any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those now if you enjoy these tutorials and would like to support them then there are several ways you can do that the easiest ways to simply like the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon and there's a link to that page and it's a strips in section below be sure to subscribe for future videos and thank you all for watching

Другие видео автора — Corey Schafer

Ctrl+V

Экстракт Знаний в Telegram

Экстракты и дистилляты из лучших YouTube-каналов — сразу после публикации.

Подписаться

Дайджест Экстрактов

Лучшие методички за неделю — каждый понедельник