Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

c# - Schedule task in ASP.NET

I'm trying to create a task scheduler that runs twice a day. I've implemented a task scheduler using CacheItemRemovedCallaback, as suggested in this post and this blog. I have the a feature that enables the admin to modified the scheduled times, and saves them on Application variables:

protected void UpdateSchedule(object sender, EventArgs e)
{
    Button button = sender as Button;
    if (button.ID == "scheduleButton1")
    {

        Application.Lock();
        Application["buildSchedule1"] = GetScheduleTime1; 
        Application.UnLock(); 
    }
    else if (button.ID == "scheduleButton2")
    {
        Application.Lock();
        Application["buildSchedule2"] = GetScheduleTime2; 
        Application.UnLock(); 
    }
    HttpRuntime.Cache.Remove(Global.DummyCachekey); //remove current scheduled task and set new time
 }

And on Global.aspx I have:

protected void Application_Start(object sender, EventArgs e)
{
    Application.Lock();
    Application["buildSchedule1"] = new TimeSpan(10,00, 0); //default time
    Application["buildSchedule2"] = new TimeSpan(16,00, 0); //default time
    Application.UnLock(); 
    SheduleTask(); 
}; 

The problem is that for some reason (probably due to app pool recycling) the schedule times get reset, and even some times the task won't start at the default times.

I found solutions that mention Windows services or Windows task scheduler, but that doesn't work for me since I need to be able to let the admin configure the times through the web application. (I search for this, but couldn't find anything).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found solutions that mention Windows services or Windows task scheduler

That's what you should be using. A web application doesn't "always run." It responds to requests, that's all. Unless something is actively making a request to the website, it's not doing anything.

but that doesn't work for me since I need to be able to let the admin configure the times through the web application

Sure it does. More than one application can share a single database. In this case you'd have two applications:

  • A Web Application where users can login and maintain the data related to the scheduled tasks.
  • A Windows Service (or scheduled Console Application) which runs in the background on the server and executes the configured tasks which it reads from the database.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...