For Hangfire, is there any sample code for non-simple tasks; and how should recurring tasks be handled when re-publishing? - asp.net

I am considering using Hangfire https://www.hangfire.io to replace an older home-grown scheduling ASP.NET web site/app.
I have created a simple test project using Hangfire. I am able to start the project with Hangfire, submit (in code) a couple of very simple single and recurring tasks, view the dashboard, etc.
I'm looking for more suggestions for creating a little more complex code (and classes) for tasks to be scheduled, and I have a question about what happens with permanently scheduled tasks when re-publishing a Hangfire site to production.
I have read some of the documentation on the Hangfire site, reviewed the 2 tutorials, scanned the Hangfire forums, and searched StackOverflow and the web a bit. A lot of what I have seen shows you how to schedule something very simple (like Console.WriteLine), but nothing more complex. The "Highlighter" tutorial was useful, but that essentially shows how to schedule a single instance of a (slightly longer-running) task in response to an interactive user input. I understand how useful that can be, but I'm more interested in recurring tasks that are submitted and then run every day (or every hour, etc.) and don't need to be submitted again. These tasks could be for something like sending a batch of emails to users each night, batch processing some data, importing a nightly feed of external data, periodically calling a web service to perform some processing, etc.
Is there any sample code available that shows some examples like this, or any guidance on the most appropriate approach for structuring such code in an interface and class(es)?
Secondly, in my case, most of the tasks would be "permanent" (always existing as a recurring task). If I set up code to add these as recurring tasks shortly after starting the Hangfire application in production, how should I handle it when publishing updates to production (when this same initialization would run again)? Should I just call "AddOrUpdate" with the same ID and Hangfire will take care of it? Should I first call "RemoveIfExists" and then add the recurring task again? Is there some other approach that should be used?

One example would be a log janitor, which would run every weekday # 5:00PM to remove logs that are older than 5 days.
public void Schedule()
{
RecurringJob.AddOrUpdate<LogJanitor>(
"Janitor - Old Logs",
j => j.OnSchedule(null),
"0 17 * * 1,2,3,4,5",
TimeZoneInfo.FindSystemTimeZoneById("CST"));
}
Then we would handle it this way
public void OnSchedule(
PerformContext context)
{
DateTime timeStamp = DateTime.Today.AddDays(-5);
_logRepo.FindAndDelete(from: DateTime.MinValue, to: timeStamp);
}
These two methods are declared inside LogJanitor class. When our application starts, we get an instance of this class then call Schedule().

Related

Simplest Way to Schedule Multiple Webjobs from DevOps

I have an app service in Azure running the front end from my MVC5 app, and another app service for web jobs. The app has several endpoints (GET Actions) which do some processing, send some emails or other simple task. Previously when we were hosted on a VPS, we used the Windows Task Scheduler to call each URL on a custom schedule. In Azure, the way we're currently doing this is with a Powershell script which uses CURL to fetch the URL and trigger the processing.
It seems messy though - as each powershell script has to be uploaded individually, and can't be viewed or changed after uploading. I've found various guides on deploying a .NET Core console app, but from what I can tell each job would need it's own project, deployed with it's own pipeline.
Is there a nicer way of doing this, are Webjobs even the right tool for this job, given the seemingly simple task we're performing.
As far as I understand your use case, you can use Azure Function App Timer Trigger to accomplish it.
A timer trigger lets you run a function on a schedule.
The following example shows a C# function that is executed each time the minutes have a value divisible by five (eg if the function starts at 18:57:00, the next performance will be at 19:00:00). The TimerInfo object is passed into the function.
[FunctionName("TimerTriggerCSharp")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
{
if (myTimer.IsPastDue)
{
log.LogInformation("Timer is running late!");
}
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}
The attribute's constructor takes a CRON expression or a TimeSpan. You can use TimeSpan only if the function app is running on an App Service plan. TimeSpan is not supported for Consumption or Elastic Premium Functions.
CRON (NCRONTAB expressions)

How to read Cron Expression from appsettings.json in .Net core Web Jobs

I have developed .Net Core 2.2 Azure Web Job project which is having multiple timer trigger functions. One function is run on every 15 minutes and other one is run on every 10 minutes.
public async Task GetRecordsFromCosmosDBCollection_0([TimerTrigger("0 0/15 * * * *")]TimerInfo timerInfo){
//Custom Business Logic
}
public async Task GetRecordsFromCosmosDBCollection_1([TimerTrigger("0 0/10 * * * *")]TimerInfo timerInfo){
//Custom Business Logic
}
If I used the CRON expression directly in the function parameters then it works as expected. But I want to read the CRON expression information from appsettings.json file and then pass it to the above two functions.
So, can anyone suggest the right approach of reading the CRON expression information from appsettings.json in Functions.cs file in Azure WebJob project.
I assume the motivation is to get the schedule out of the compiled code where it can be changed without having to re-compile and re-deploy.
This might not be the most elegant solution - but you could put your two functions into two different scheduled WebJobs. Then you could set a separate settings.job for each one.
https://learn.microsoft.com/en-us/azure/app-service/webjobs-create#CreateScheduledCRON
The external settings.job file is deployed to the folder where the WebJob exe is - typically D:\home\site\wwwroot\App_Data\jobs\triggered\WebJobName - and you could change the schedule there.
To have different schedules - you'd have to split into different WebJobs because the settings.job schedule is kicking off Main, as opposed to a specific function like [TimerTrigger].
In a scheduled job, the code in Main would look like this:
await host.StartAsync();
await jobHost.CallAsync("ManualTrigger", inputs);
await host.StopAsync();
where "ManualTrigger" is the function in Functions.cs. The schedule in settings.jobs kicks off Main, runs the function, and then shuts down.

is it possible to auto update data every day on firebase [duplicate]

Is it possible on Firebase or Parse to set up something kinda like a cron job?
Is there a way to set up some sort of timed operation that runs over the stored user data?
For example, I'm writing a program that allows people to RSVP for lunch everyday. If you have RSVPed by noon, then you get paired up with somebody else who has also RSVPed. Using JavaScript, the user can submit their RSVP in the browser.
The question is, can Firebase/Parse execute the code to match everyone at 12:00pm every day?
Yes, this can be done with Parse. You'll need to write your matching function as a background job in cloud code, and then you'll need to schedule the task in the dashboard. In terms of the flexibility in scheduling, it's not as flexible as cron but you can definitely run a task at the same time every day, or every x minutes/hours.
Tasks can take 15 mins max to execute before they're killed, so depending on the size of your database or the complexity of your task, you may need to break it up into different tasks or make it resumable.
Just to confirm about Firebase:
As #rickerbh said, it can be done with Parse, but currently there is no way for you to run your code on Firebase's server. There are 2 options for you 2 solve this:
You could use Firebase Queue and run your code in Node.js
You could use a different library such as Microsoft Azure (I still haven't tried this yet, I'm not sure if it provides Job Scheduling for Android)
However, Firebase is working on something called Firebase Trigger, which will solve our problem, however it is still not released with no confirmed release date.

How to do scheduled tasks in ASP.NET?

I am coding a text based web browser game in ASP.NET. But i need a lil bit info so i decided to ask here.
When user enter any quest, lets say that quest take 10 mins to proceed. If user exits from game, how can i make my script to run automaticly and finish the quests and upgrade players power etc? I heard something like CronJob. But i dont know if it works for ASP.NET so i wanna hear any idea before i do this. Thank you for your help.
You could just add a cache item with a callback function.
public void SomeMethod() {
var onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
Cache.Add("UserId_QuestId", "AnyValueYouMightNeed", null, DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove);
}
public void RemovedCallback(String key, Object value, CacheItemRemovedReason r){
// Your code here
}
The cache item has an expiration of 10 minutes, and as soon as it is removed from memory the RemovedCallback will be invoked.
Note: just to completely answer your question:
You could also use some of the frameworks available to schedule tasks in asp.net (such as Quartz.net).
Create a Console project in your solution and schedule it on the Web server (using the Windows Scheduler).
Create a Web Job project, if you are deploying your web in Azure.
But in your situation, using the cache is probably the simplest solution.

Guidance on how to build a scheduler in ASP.NET MVC 4

I have a simple question to ask.. Does anyone know how to create a repetitive scheduler in ASP.NET MVC 4. What I'm attempting to build is an Irrigation System that I can set the days of the week and times for my system to activate each week. So the user would select the Day of the week along with the time and duration the system should run. How do I keep a running clock that triggers the system to turn on?.. Should I use a drop down list for my properties? Although it would be nice, I'm not asking for you to write an entire application for me.. A simple point in the right direction would help tremendously.. The problem with searching for the answers over the net is I really don't know what to search for.
Thank you in advance..
We are using Quartz.Net exactly for this. It is a port of Quartz for Java.
It is very powerful and it is quite easy to define new jobs (what should be done) and schedules (when to do it).
The new versions support a Cron scheduler which supports linux cron like configuration - so it is quite easy to start a job on every monday, or on every 5th of the month or for every 5 minutes on a given date. I think it's hard for scheduled tasks to beat this flexibility.
We are using the database configuration and a service on the server (this is the "running clock which activates things). Additionally a web services is used to configure the Quartz scheduler and the running service is changed through the database (this is done by Quartz.Net for you). All these things are supported nicely with it.
Some tips to start with cron triggers:
First thing would be the tutorial from http://quartznet.sourceforge.net/tutorial/lesson_1.html .
Lessons 1 - 3 show you the basic building blocks. Lesson 9 shows you the ADO job store (for db persistance).
Working with the cron trigger would work like this
ITrigger trigger = TriggerBuilder.Create().WithIdentity(id).StartNow().WithCronSchedule(cronstring).Build();
scheduler.ScheduleJob(job, trigger);
To give you an idea of the possibilites of the cron trigger this guide comes handy.
Follow this link:
http://scheduler-net.com/docs/simple_.net_application_with_scheduler.html
http://blog.scheduler-net.com/post/2012/10/29/5-Steps-to-a-Simple-Scheduler-in-ASPNET-MVC3MVC4.aspx
Scheduler for Web application ASP.NET MVC
Friend, you can create a scheduler with the help of following code
void Application_Start(object sender, EventArgs e)
{
System.Threading.Timer _timer = new System.Threading.Timer(
new TimerCallback(GetProducts));
_timer.Change(0, 51000); // here you can change the start time interval
}
static void GetProducts(Object state)
{
// do something
}
To make scheduled tasks on an independent date time server, and get detailed reports about all tasks, you can use A Trigger as a scheduling service. abilities such as pause, resume or delete sets of tasks using tags, archiving and storing all call results such as possible errors will really help developers independent of the programming language.
.Net library is also available:
//Create
ATrigger.Client.doCreate(TimeQuantity.Day(), "1", "http://www.example.com/myTask?something", tags);
Disclaimer: I was amoung ATrigger builders. It's an absolutely freeware, not commercial purpose.

Resources