How to add email scheduler in asp.net? - asp.net

I want to configure e-mail scheduler in an Asp.net web application and I don't know how to achieve this thing. Does anybody have any idea how I can achieve this? I just want to send emails at specific time.

You can use scheduler frameworks such as Quartz.net. You can create Jobs in Quartz.net and creates triggers. Triggers kicks in the job at particular time, day, month, nightly basis etc etc. You will be using Cron scheduler to schedule your jobs (that is triggers).

I think the easiest way would be to write a good old fashioned console program which sends the emails when it runs. Then you simply use a scheduler to run it on the time(s) you want.

I use next solution.
In your Global.asax add this line to Application_Start method:
this.Application["Timer"] = new Timer(new TimerCallback(EMailProcessor.Process), null, 0, 60000);
Your EMailProcessor class may look like:
public class EMailProcessor
{
public static void Process(object state)
{
// Your code here
}
}
Hope this is what you need.
UPD: This works because the asp.net application are 'real' applications and running even there are no requests to the server.

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)

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

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().

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.

IIS7 is it possible to get it to run a webpage every 5 mins?

I have IIS7.5. We currently have a weighted rating for entities on our website. Calculating the weighted rating is extremely slow, to the point loading the homepage now takes more than 10 seconds to load.
To solve this, I'd like to store the weighting in the database with each entity, and have IIS run a script every 5-10 minutes that recalculates the weightings.
How do I go about doing this? It would be easiest for me if it ran a webpage URL.
One approach is to use a Windows service for this rather than calling a web URL.
This can then run completely out-of-band in the background to perform calculations. Details on this are here:
http://msdn.microsoft.com/en-us/library/d56de412%28v=VS.100%29.aspx
A few advantages include:
Your IIS process will not be affected, so your users will see no slowdown
The service can be stopped or started independently of the Web site
However, you'll need to have reasonably full access to the server to install and run the service.
You can use a Cache entry for this, set to expire 10 minutes in the future.
When you add the item, use a callback function for the CacheItemRemovedCallback parameter - in this callback function do your database work and re-add the expiring cache entry.
Other options include:
Using one of the timer classes included in the BCL - there is a MSDN magazine article describing and comparing the different ones.
Writing a windows service to do this.
Using a scheduled task.
Windows service and schedules tasks still require you to have some way to communicate the results to IIS.
To not use client, only server to continuously call this function, you can create a thread on the server to call the function that calculates it.
A better way to start the thread or timer is in the Global.asax, like this sample:
public class Global : System.Web.HttpApplication
{
private Timer _timer;
void Application_Start(object sender, EventArgs e)
{
int period = 1000 * 60 * 10; // 10 minutes
_timer = new Timer(TimerCallback, null, 1000, period);
}
private void TimerCallback(object state)
{
// Do your stuff here
}
}
}
I have done something like this earlier and I had used windows scheduled tasks to call my script at specific intervals of time.
A simple batch file with WGET or similar, and help from Scheduled Tasks will do it.
http://www.gnu.org/software/wget/
you can try this to test this idea:
wget http://localhost/filename.ashx

Resources