Reputation: 408
I'm trying to call a function at a regular interval.
The code below is written in the global.asax.cs
file and it's working is ScheduleTaskTrigger()
calls CheckLicenseExpiry()
after 1 min. But I also want to call this function every , let's say 4 hrs.
is there anyway for achieving this by changing this code:
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//used here formating API//
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
ScheduleTaskTrigger();
}
static void ScheduleTaskTrigger()
{
HttpRuntime.Cache.Add("ScheduledTaskTrigger",
string.Empty,
null,
Cache.NoAbsoluteExpiration,
// TimeSpan.FromMinutes(60), // Every 1 hour
// TimeSpan.FromMinutes(0.0167),
TimeSpan.FromMinutes(1),
CacheItemPriority.NotRemovable,
new CacheItemRemovedCallback(CheckLicenseExpiry));
}
static void CheckLicenseExpiry(string key, Object value, CacheItemRemovedReason reason)
{
CompanyHelper.CheckLicenseExpired();
}
Upvotes: 1
Views: 672
Reputation: 22456
As I read from your sample, you want to check whether a license has expired on a regular basis. Solving this using the ASP.NET cache - which might work but maybe not in all scenarios (ASP.NET cache was built for a different purpose). Also, using timers is not a good idea as the application pool of the web application might not be running thus the task will not be executed.
Instead you could check on each request whether the license has expired. In order to save performance, you could only check if the last check was done more than 4 hours ago.
In ASP.NET MVC you can create an ActionFilter or AuthorizationFilter that implements this logic. You can apply this filter either globally to all routes or only to specific routes/controllers/actions.
As you want to block access to your site if the check is not successful, a custom AuthorizationFilter is a good approach. For details on ActionFilters, see this link, for a sample on implementing a custom AuthorizationFilter, see this link.
In the filter, you should be aware that there can be parallel requests that access the variable that stores the time of the last check. So you need to lock the resources in a appropriate way.
Upvotes: 1
Reputation: 2585
I recommend using Quartz.Net.
Global.asax
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
Scheduler.Start();
}
void Application_End(object sender, EventArgs e)
{
Scheduler.Stop();
}
}
Scheduler.cs (helper class)
using Quartz;
using Quartz.Impl;
public class Scheduler
{
private static IScheduler _scheduler;
public static void Start()
{
_scheduler = StdSchedulerFactory.GetDefaultScheduler();
_scheduler.Start();
ITrigger myTrigger = TriggerBuilder.Create()
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInHours(4)
.RepeatForever())
.Build();
IJobDetail myJob = JobBuilder.Create<MyJobClass>().Build();
_scheduler.ScheduleJob(myJob, myTrigger);
}
public static void Stop()
{
if (_scheduler != null)
{
_scheduler.Shutdown();
}
}
}
MyJobClass.cs
[DisallowConcurrentExecution]
public class MyJobClass : IJob
{
public void Execute(IJobExecutionContext context)
{
//do something
}
}
I hope this helps.
Upvotes: 1
Reputation: 17850
Please use the System.Threading.Timer
(MSDN link). It provides a mechanism for executing a method at specified intervals and does not depends on platform:
new System.Threading.Timer(_ =>
{
// do something here
},
null,
TimeSpan.FromMinutes(1) /*dueTime*/,
TimeSpan.FromHours(1) /*period*/
);
Upvotes: 1
Reputation: 1006
If you're willing to use Windows Forms, use the "Timer" class.
using System.Windows.Forms;
//[...]
Timer timer;
private void Initialiser()
{
Timer timer = new Timer();
timer.Interval = 3600000;//Set interval to an hour in the form of milliseconds.
timer.Tick += new EventHandler(timer_Tick);
}
private void timer_Tick(object sender, EventArgs e)
{
//The function you wish to do every hour.
}
You can change the interval to anything given that it is in the form of milliseconds (1000 per second). (e.g. 1 minute: 60000, 4 hours: 14400000).
P.S You can just use the "System.Windows.Forms" library without necessarily having a Windows Forms program, I imagine you could use this code in WPF also).
Upvotes: 1