Create and deploy Azure web job in .net core
What: WebJob is the program which runs in background . In
another word it’s a kind of scheduler which can be run based on cron, or
manual call.
Type – there are 2 types of webjob
A.
Continuous – run 24X7 immediately after publish
B.
Triggered – can run based on corn setting or can
be triggered manually by webhook/ directly from azure portal.
Language/script Support:
1.
cmd,
.bat, .exe
2.
.ps1
(using powershell)
3.
.sh
(using bash)
4.
.php
(using php)
5.
.py
(using python)
6.
.js
(using node)
Requirement
- Azure
App service – each app service has webjob by default . no need to take separate
service for webjob.
- Azure Storage account –
- Make sure you have install azure
sdk while installing Visual studio if not you can modify and choose azure..
How to create and deploy
We will create two type of webjobs
- Sending
email to all subscriber
- Reszie
the blob image after uploading via webjob
Lets Start with first one:
1- Assume
we have list of subscribers and we need to send them email with new news/product
get entered in the system. Here instead of locking thread from code we can use
web job to send email from background which makes system faster and end user who
submit news no need to wait ..
In order to implement this lets follow below steps
1. Login
to azure portal ->go to your storage account-> search access key -> copy
you connection string and keep somewhere in you local computer , we need it
later.
2.
Open
Visual Studio and Create new web job project
Basically, it’s a console application
with program.cs and function.cs file.
3. Open app.config file and paste
you azure storage connection string in below two section. Both AzurewebjobDashboard and AzurewebjobsStorage could be the same.
4. Now open function.cs file and
write your logic to send email to all subscriber , in below code I am using gmail to send email. you can use whatever you want.
using Microsoft.Azure.WebJobs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading;
namespace azwebjoblearn
{
public class Functions
{
// This function will get triggered/executed when a new message is written
// on an Azure Queue called queue.
public static void ProcessQueueMessage([QueueTrigger("queue")]
string message, TextWriter log)
{
log.WriteLine(message);
}
[NoAutomaticTrigger]
public void TriggerHandler(TextWriter log)
{
//here you can put whatever your logic based on your requirement like fetch data from db,email, stock update etc.
try
{
Console.WriteLine("web job function triggered");
// log.WriteLine("web job function triggered");
SendEmailToSubscriber();
}
catch (Exception ex)
{
log.WriteLine("Exception in Trigger Handler", ex);
throw ex;
}
}
private void SendEmailToSubscriber()
{
//subscriber list
var subscripberList = new List<string>();
subscripberList.Add("m222@gmail.com");
subscripberList.Add("test1@gmail.com");
subscripberList.Add("test2@gmail.com");
subscripberList.Add("test3@gmail.com");
subscripberList.Add("stes4@gmail.com");
subscripberList.Add("test5@gmail.com");
var mailMessage = new MailMessage();
var fromAddress = new MailAddress("webjobtesting@gmail.com", "webjobs");
foreach (var item in subscripberList)
{
mailMessage.To.Add(new MailAddress(item , "To Name"));
}
mailMessage.From = fromAddress;
mailMessage.Subject = "News posted for you";
mailMessage.Body = "Dear subscriber , one news posted in portal";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("hhhhhh.com", "knnnnn")
};
try
{
smtp.Send(mailMessage);
}
catch(Exception ex)
{
throw ex;
}
}
}
}
5. Now Open the Program.cs and copy below code
namespace azwebjoblearn
{
// To learn more about Microsoft Azure WebJobs SDK, please see https://go.microsoft.com/fwlink/?LinkID=320976
class Program
{
// Please set the following connection strings in app.config for this WebJob to run:
// AzureWebJobsDashboard and AzureWebJobsStorage
static void Main()
{
var config = new JobHostConfiguration();
if (config.IsDevelopment)
{
config.UseDevelopmentSettings();
}
var host = new JobHost(config);
//host.call will call the triggerHandler function based on schedule or call
host.Call(typeof(Functions).GetMethod("TriggerHandler"));
//to make it continuous use host.RunAndBlock(); and pass timer parameter in TriggerHandler function
// host.RunAndBlock();
}
}
}
6. Open Settings.job file and put your required corn , u can keep all commented also ,depend on your requirement.
{
// Examples:
// Runs every minute
"schedule": "0 * * * * *"
// Runs every 15 minutes
// "schedule": "0 */15 * * * *"
// Runs every hour (i.e. whenever the count of minutes is 0)
// "schedule": "0 0 * * * *"
// Runs every hour from 9 AM to 5 PM
// "schedule": "0 0 9-17 * * *"
// Runs at 9:30 AM every day
// "schedule": "0 30 9 * * *"
// Runs at 9:30 AM every week day
// "schedule": "0 30 9 * * 1-5"
}
Here our coding part is done, need to publish now.
we can publish webjobs by three ways
1.directly from visual studio
2. make zip file and upload manually in azure app service
3.Through CI/CD
I am going to use first approach
1.select publish option and configure your select your azure subscription ->resource group->app service
After selecting your app service click finish. After published successfully go to Azure Portal -> App service- webjobs here you can see deployed web job -
Now you can click on Run and all subscriber should get email ..
In next section will see how to trigger this web job from web api..
Thanks
No comments:
Post a Comment
Thanks for your valuable comments