How to schedule tasks in .NET? We've made it seem easy #2
Tags: dotnet, csharp, tutorial, beginners
Published: 2021-11-18 08:25:29

Welcome to the second part of the series about "URL shortener in .NET". In the first post of this series we created simple URL shortener web service, and tested it manually with Postman. Check [part one](https://dev.to/infobipdev/how-to-write-url-shortener-in-net5-weve-made-it-seem-easy-1-5c56) here or skip it if you only want to find out how to schedule services in .NET.

In part two, we want to expand functionality of our web service with some additional features, such as SMS reports.

**This post aims to show you:**

* How to send SMS 

* How to easily add scheduler to our web service

* How to send SMS periodically 

Use my [github](https://github.com/dlozina/url-shortener-service-v2) to find a finished project and avoid the nuisance of writing the code yourself.


###📱 **First Step: Send SMS** ✔️

For our SMS provider we will use Infobip. Please access our free trial self service account through this [link](https://www.infobip.com/docs/api). After grabbing our API key and URL you just need to implement client library in the project. 

Library: ([github](https://github.com/infobip/infobip-api-csharp-client))

```
dotnet add package Infobip.Api.Client
```

Then, place your user settings in *appsettings.json*, so that you can easily grab them through our web app.

{% gist https://gist.github.com/dlozina/f86ce5f0692d836c25b8ee22ce0b5af4 file=appsettings01.json %}

Based on Infobip library, we will create method SendNotificationSms:

{% gist https://gist.github.com/dlozina/f86ce5f0692d836c25b8ee22ce0b5af4 file=SendSms.cs %}


Let's go through `SendNotificationSms(string smsNotificationMessage)`. 
* First, we set up the configuration we will send to `SendSmsApi` class.
* Then create `SmsTextualMessage` by setting up Form, Destination and Text fields.
* Finally, add created message to `SmsAdvancedTextualRequest`.

SendSmsMessage method from Infobip library will do the trick and send the message to our user:

```csharp
var smsResponse = sendSmsApi.SendSmsMessage(smsRequest); 
```

Now that the basic functionality is up and running, adding it to your scheduler shouldn't be a problem. 

### ⏰ **Second Step: Add scheduler** ✔️

For this feature we will use Quartz.NET. 
One could describe Quartz.NET as a full-featured, open-source job-scheduling system.

There are two important points you need to know; Job Scheduling and Job Execution.

**1. Job Scheduling**

* Jobs are scheduled to run when a given trigger occurs, triggers support wide variety of scheduling options.

**2. Job Execution**

* Jobs can be any .NET class that implements the simple `IJob` interface, leaving infinite possibilities for the work that jobs can perform.

Lets's add package to our project:

```
dotnet add package Quartz.Extensions.Hosting
```

Now, we have to configure and register our Quartz service. Use *Program.cs* for that. You can follow documentation https://www.quartz-scheduler.net/ on how to configure and register in detail. 

{% gist https://gist.github.com/dlozina/f86ce5f0692d836c25b8ee22ce0b5af4 file=Program.cs %}

In this code example, we try to keep *Program.cs* as short as possible, hence the extension method for our settings.

{% gist https://gist.github.com/dlozina/f86ce5f0692d836c25b8ee22ce0b5af4 file=ServiceCollectionQuartzConfiguratorExtensions.cs%}

### ⏲️ **Third Step: Send SMS periodically** ✔️

Scheduler is all set up and now you need to add jobs. In our report feature we decided to send SMS messages daily, weekly and monthly. 

Example [project](https://github.com/dlozina/url-shortener-service-v2) has three jobs defined in project Jobs folder.

Remember: 
> Jobs can be any .NET class that implements the simple `IJob` interface.

Example code below sends daily SMS report of how many URLs are shortened:

{% gist https://gist.github.com/dlozina/f86ce5f0692d836c25b8ee22ce0b5af4 file=SendDailyNotification.cs %}

You may ask yourself: Where is the scheduled time in this code? How can I change it?

Well…that is the beauty of Quartz - it uses Cron expression which is easy to set up.
For example, we have moved scheduler setup to our application settings, so there are separate settings for every job in our application.

{% gist https://gist.github.com/dlozina/f86ce5f0692d836c25b8ee22ce0b5af4 file=appsettings02.json %}

You can check out for various settings on [cron triggers](https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/crontriggers.html)

In our example:

* Cron expression: "0 0 8 ? * MON-SUN" -> Daily - MON-SUN on 08:00 CET for the previous day

* Cron expression: "0 1 8 ? * MON" -> Weekly - MON on 08:01 CET for the past week

* Cron expression: "0 2 8 * * MON#1" -> Monthly - first MON on the month for the past month

If you go back to *Program.cs* you will see how we grab and use this settings with our extension method.

Now our web service is ready to send scheduled reports to users.

###***Conclusion 🎉 🍾***
It comes as no surprise that scheduling jobs in applications can be a really daunting work. Quartz makes it so much easier. Bare in mind that we just scratched the surface with our settings. There is a lot more stuff under the hood but probably this is enough for most of use cases.

The same thing can be said about our SMS notification feature. You don't need to write API request to Infobip platform. Just add library to your .NET project, set config, create your message objects and than send an SMS. It is also possible to expand this simple example and send reports with other
information channels, such as Email and Whatsapp.
Find other available options on [Infobip Api](https://www.infobip.com/docs/api).

Stay well,

Dino