Monday, December 4, 2017

Task Scheduling in Laravel

In this article, we’ll go through one of the exciting features of the Laravel web framework—task scheduling. Throughout the course of this article, we’ll look at how Laravel allows you to manage scheduled tasks in your application. Moreover, we’ll also end up creating our own custom scheduled tasks for demonstration purposes.

The Laravel framework allows you to set up scheduled tasks so that you don't have to worry about setting them up at the system level. You can get rid of that complex cron syntax while setting up scheduled tasks since Laravel allows you to define them in a user-friendly way.

We’ll start the article with how you are used to setting up traditional cron jobs, and following that we’ll explore the Laravel way of achieving it. In the latter half of the article, we’ll give it a try by creating couple of custom scheduled tasks that should provide hands-on insight into the subject.

Traditional Scheduled Task Setup

In your day-to-day application development, you often face a situation that requires you to execute certain scripts or commands periodically. If you're working with the *nix system, you are probably aware that cron jobs handle these commands. On the other hand, they're known as scheduled tasks on Windows-based systems.

Let's have a quick look at a simple example of the *nix based cron job.

Pretty simple—it runs the statistics.sh file every five minutes!

Although that was a pretty simple use case, you often find yourself in a situation that requires you to implement more complex use cases. On the other hand, a complex system requires you to define multiple cron jobs that run at different time intervals.

Let's see some tasks a complex web application has to perform periodically in the back-end.

  • Clean up the unnecessary data from the database back-end.
  • Update the front-end caching indexes to keep it up-to-date.
  • Calculate the site statistics.
  • Send emails.
  • Back up different site elements.
  • Generate reports.
  • And more.

So, as you can see, there's plenty of stuff out there waiting to be run periodically and also at different time intervals. If you're a seasoned system admin, it's a cake walk for you to define the cron jobs for all these tasks, but sometimes we as developers wish that there was an easier way around.

Luckily, Laravel comes with a built-in Task Scheduling API that allows you to define scheduled tasks like never before. And yes, the next section is all about that—the basics of Laravel task scheduling.

The Laravel Way

In the earlier section, we went through the traditional way of setting up cron jobs. In this section, we'll go through the specifics of Laravel in the context of the Task Scheduling API.

Before we go ahead, the important thing to understand is that the scheduling feature provided by Laravel is just like any other feature and won't be invoked automatically. So if you're thinking that you don't need to do anything at the system level then you're out of luck, I'd say.

In fact, the first thing you should do should you wish to use the Laravel scheduling system is to set up the cron job that runs every minute and calls the artisan command shown in the following snippet.

The above artisan command calls the Laravel scheduler, and that in turn executes all the pending cron jobs defined in your application.

Of course, we are yet to see how to define the scheduled tasks in your Laravel application, and that's the very next thing we'll dive into.

It's the schedule method of the App\Console\Kernel class that you need to use should you wish to define application-specific scheduled tasks.

Go ahead and grab the contents of the app/Console/Kernel.php file.

As you can see, the core code itself provides a useful example. In the above example, Laravel runs the inspire artisan command hourly. Don't you think that the syntax is so intuitive in the first place?

In fact, there are a couple of different ways in which Laravel allows you to define schedule tasks:

  • Use the closure/callable.
  • Call the artisan command.
  • Execute the shell command.

Moreover, there are plenty of built-in scheduling frequencies you could choose from:

  • every minute/every five minutes
  • hourly/daily/weekly/quarterly/yearly
  • at a specific time of the day
  • and many more

In fact, I would say that it provides a complete set of routines so that you don't ever need to touch the shell to create your custom cron jobs!

Yes I can tell that you're eager to know how to implement your custom scheduled tasks, and that is what I also promised at the beginning of the article.

Create Your First Scheduled Task in Laravel

As we discussed, there are different ways in which Laravel allows you to define scheduled tasks. Let's go through each to understand how it works.

The Closure/Callable Method

The scheduling API provides the call method that allows you to execute a callable or a closure function. Let's revise the app/Console/Kernel.php file with the following code.

As you can see, we've passed the closure function as the first argument of the call method. Also, we've set the frequency to every 30 minutes, so it'll execute the closure function every 30 minutes!

In our example, we count the total posts per user and update the statistics table accordingly.

The Artisan Command

Apart from the closures or callables, you could also schedule an artisan command that will be executed at certain intervals. In fact, that should be the preferred approach over closures as it provides better code organization and reusability at the same time.

Go ahead and revise the contents of the app/Console/Kernel.php file with the following.

It's the command method that you would like to use should you wish to schedule an artisan command as shown in the above code snippet. You need to pass the artisan command signature as the first argument of the command method.

Of course, you need to define the corresponding artisan command as well at app/Console/Commands/UserStatistics.php.

The Exec Command

We could say that the methods we've discussed so far were specific to the Laravel application itself. Moreover, Laravel also allows you to schedule the shell commands so that you could run external applications as well.

Let's go through a quick example that demonstrates how to take a backup of your database every day.

It's apparent from the code that you need to use the exec method of the scheduler, and you need to pass the command that you would like to run as its first argument.

Apart from that, we've also used the sendOutputTo method that allows you to collect the output of the command. On the other hand, there's a method, emailOutputTo, that allows you to email the output contents!

And that brings us to the end of the article. In fact, we've just scratched the surface of the Laravel Scheduling API, and it has a lot to offer in its kitty.

Conclusion

Today, we went through the task scheduling API in the Laravel web framework. It was fascinating to see how easily it allows you to manage tasks that need to be run periodically.

At the beginning of the article, we discussed the traditional way of setting up scheduled tasks, and following that we introduced the Laravel way of doing it. In the latter half of the article, we went through a couple of practical examples to demonstrate task scheduling concepts.

I hope that you’ve enjoyed the article, and you should feel more confident about setting up scheduled tasks in Laravel. For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study in Envato Market.

Should anything pop up in your mind, let’s start a conversation using the feed below!


by Sajal Soni via Envato Tuts+ Code

How to Use the Facebook Creator App

Want to add more polish to your Facebook Live broadcasts? Wondering how Facebook Creator can help? Facebook Creator is a handy all-in-one app that lets you record branded video, chat with your community, and get valuable insights for your content. In this article, you’ll discover how to use the Facebook Creator mobile app to get [...]

This post How to Use the Facebook Creator App first appeared on .
- Your Guide to the Social Media Jungle


by Peg Fitzpatrick via

X

Neat hover-sensitive color bar effect in this launching soon page for a contemporary art and design online platform called X. Nice touch with the multiple-X animation for the favicon.

Full Review | Direct Link


by Rob Hope @robhope via One Page Love

5 Fantastic Places to Find Background Music for Your Video Content

As a video creator you might have experienced that finding quality background music for your videos can be a time-consuming task. So, to make your job less miserable, here's a list of 5 great websites for finding public domain and royalty free music for your online videos.

[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Irfan Ahmad via Digital Information World

Win Free Tickets to Social Media Marketing World 2018

Want to win a free ticket to the industry’s largest social media marketing conference of the year? Social Media Examiner has been working hard to bring you our sixth annual physical conference. And we’ve come up with a fun way for you to get involved. First, what is this event? Social Media Marketing World 2018 [...]

This post Win Free Tickets to Social Media Marketing World 2018 first appeared on .
- Your Guide to the Social Media Jungle


by Phil Mershon via

Tapwater

Clean long-scrolling Landing Page (and redesign) for communication tool, Tapwater.

Full Review | Direct Link


by Rob Hope @robhope via One Page Love

How ‘Microbloggers’ Leverage Their Influence Through Social Media Savvy - #infographic

Ever since the line between celebrity and social media celebrity was erased, bloggers have become legitimate influencers across almost all industries, affecting consumer decisions beyond purchasing by acting as both tastemaker and trusted friend. And a large fan base is no longer a requirement for...

[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Web Desk via Digital Information World