我在Visual Studio Web Express中有Web应用程序,在sql Server Express中有db。我想每天下午 5:00 执行插入 100 条记录.Web 应用程序是在 MVC 和 vb.net asp.net 开发的。并使用 IIS 7.5 部署在服务器计算机上。我应该遵循什么逻辑?
我正在使用这种方法,到目前为止它很好:)
我已经枚举了要执行的任务和任务重新启动的时间,这次以秒为单位,如下所示:
public enum ScheduledTasks
{
CleanGameRequests = 120,
AnotherTask = 30,
}
然后,我在Application_Start
中启动所有任务,以确保任务将在应用程序运行时执行
protected void Application_Start()
{
...............
// Add the tasks on Application starts
AddTask(ScheduledTasks.CleanGameRequests);
AddTask(ScheduledTasks.AnotherTask);
}
好的,现在这是诀窍:)
在AddTask方法中,我只是将新的空项添加到缓存中,并根据任务时间和为此任务调用合适的方法为其设置绝对过期。
实际上我的我无法非常清楚地解释这个想法,但这是代码:
private static CacheItemRemovedCallback _onCacheRemove;
private void AddTask(ScheduledTasks task)
{
// Add my `CacheItemRemoved` method to be called on cache removed
_onCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
// Add new key to the cache with the name of this task
// and Expiration time acccordin to the task
HttpRuntime.Cache.Insert(task.ToString(), (int)task, null,
DateTime.Now.AddSeconds((int)task), Cache.NoSlidingExpiration,
CacheItemPriority.NotRemovable, _onCacheRemove);
}
然后我所要做的就是在CacheItemRemoved
方法中为每个任务选择合适的方法:
public void CacheItemRemoved(string key, object time, CacheItemRemovedReason r)
{
//Get Task enum object
var task = (ScheduledTasks)Enum.Parse(typeof(ScheduledTasks), key);
// Select the suitable method to depending on the Task Enum object
switch (task)
{
case ScheduledTasks.CleanGameRequests:
GameRequest.CleanUp();
break;
case ScheduledTasks.AnotherTask:
Service.AnotherTask();
break;
}
// Don't forget to re-add the task to the cache to do it again and again
AddTask(task);
}
您的案例的最后一件事是检查时间是否是下午 5:00,我建议您将此检查放在您的服务类中。
希望这对你有所帮助:)
由于您使用的是 Sql 服务器速成版,因此无法在 SQL 端创建计划作业。但是您可以尝试其他选项,例如。
-
Quartz.Net
-
服务代理方法
-
Windows 服务(如果您的托管服务提供商允许)