当前位置: 移动技术网 > IT编程>开发语言>.net > Asp.Net(C#)自动执行计划任务的程序实例分析分享

Asp.Net(C#)自动执行计划任务的程序实例分析分享

2017年12月12日  | 移动技术网IT编程  | 我要评论
在业务复杂的应用程序中,有时候会要求一个或者多个任务在一定的时间或者一定的时间间隔内计划进行,比如定时备份或同步数据库,定时发送电子邮件等,我们称之为计划任务。实现计划任务

在业务复杂的应用程序中,有时候会要求一个或者多个任务在一定的时间或者一定的时间间隔内计划进行,比如定时备份或同步数据库,定时发送电子邮件等,我们称之为计划任务。实现计划任务的方法也有很多,可以采用sqlagent执行存储过程来实现,也可以采用windows任务调度程序来实现,也可以使用windows服务来完成我们的计划任务,这些方法都是很好的解决方案。但是,对于web应用程序来说,这些方法实现起来并不是很简单的,主机服务提供商或者不能直接提供这样的服务,或者需要你支付许多额外的费用。 本文就介绍一个直接在web应用程序中使用的简单的方法,这个方法不需要任何额外的配置即可轻松实现。

由于asp.net站点是作为web应用程序运行的,它并不受线程的限制,因此我们可以非常方便地在application_start和application_end事件中建立和销毁一个计划任务。下面就简单介绍一下在web站点实现计划任务的方法。我们的例子是定时往文件里添加信息,作为例子,这里把当前的时间定时地写入文件中。

一个计划任务的工作单元称之为一个任务(job),下面的代码描述了对所有任务都可以被调度引擎计划执行的一个通用的接口,这里的每个任务实现了execute方法,供调度引擎进行调用:

复制代码 代码如下:

public interface ischedulerjob
{
void execute();
}

如前所述,我们的例子是实现往文件写如字符日期,下面就是实现这一任务的方法:

复制代码 代码如下:

public class samplejob : ischedulerjob
{
public void execute()
{
//文件保存的物理路径,cstest为虚拟目录名称,f:\inetpub\wwwroot\cstest为物理路径
string p = @"f:\inetpub\wwwroot\cstest";
//我们在虚拟目录的根目录下建立schedulerjob文件夹,并设置权限为匿名可修改,
//schedulerjob.txt就是我们所写的文件
string file_name = p+ "\\schedulerjob\\schedulerjob.txt";
//取得当前服务器时间,并转换成字符串
string c = system.datetime.now.tostring("yyyy-mm-dd hh:mm:ss");
//标记是否是新建文件的标量
bool flag = false;
//如果文件不存在,就新建该文件
if (!file.exists(file_name))
{
flag = true;
streamwriter sr = file.createtext(file_name);
sr.close();
}
//向文件写入内容
streamwriter x = new streamwriter(file_name,true,system.text.encoding.default);
if(flag) x.write("计划任务测试开始:");
x.write("\r\n"+c);
x.close();
}
}

接下来,我们建立一个配置对象,告诉调度引擎执行什么任务和执行的时间间隔。

复制代码 代码如下:

public class schedulerconfiguration
{
//时间间隔
private int sleepinterval;
//任务列表
private arraylist jobs = new arraylist();

public int sleepinterval { get { return sleepinterval; } }
public arraylist jobs { get { return jobs; } }

//调度配置类的构造函数
public schedulerconfiguration(int newsleepinterval)
{
sleepinterval = newsleepinterval;
}
}

下面就是调度引擎,定时执行配置对象的任务

复制代码 代码如下:

public class scheduler
{
private schedulerconfiguration configuration = null;

public scheduler(schedulerconfiguration config)
{
configuration = config;
}

public void start()
{
while(true)
{
//执行每一个任务
foreach(ischedulerjob job in configuration.jobs)
{
threadstart mythreaddelegate = new threadstart(job.execute);
thread mythread = new thread(mythreaddelegate);
mythread.start();
thread.sleep(configuration.sleepinterval);
}
}
}
}

所有的准备工作已经完成,下面就是激活引擎的工作了。为了让我们的任务计划执行,我们在global.asax.cs文件里的applicatio_start和application_end里进行建立和销毁工作,首先建立一个调度进程运行的线程,我们这里的运行间隔时间为3秒钟。

复制代码 代码如下:

public system.threading.thread schedulerthread = null;
protected void application_start(object sender, eventargs e)
{
schedulerconfiguration config = new schedulerconfiguration(1000*3);
config.jobs.add(new samplejob());
scheduler scheduler = new scheduler(config);
system.threading.threadstart mythreadstart = new system.threading.threadstart(scheduler.start);
system.threading.thread schedulerthread = new system.threading.thread(mythreadstart);
schedulerthread.start();
}

最后还需要在程序退出时进行销毁:

复制代码 代码如下:

protected void application_end(object sender, eventargs e)
{
if (null != schedulerthread)
{
schedulerthread.abort();
}
}

好了,在vs.net里建立一个c#的web应用程序工程,建立taskscheduler.cs类,并修改相应的global.asax.cs文件。为了能看到效果,我们再建立一个表单webform1.aspx,定时刷新来检查我们所记录的数据:

复制代码 代码如下:

<%@ page language="c#" codebehind="webform1.aspx.cs" autoeventwireup="false"
inherits="cstest.webform1" %>
<!doctype html public "-//w3c//dtd html 4.0 transitional//en" >
<html>
<head>
<title>在web应用程序中执行计划任务的例子</title>
<meta http-equiv="refresh" content="10">
<meta name="generator" content="microsoft visual studio 7.0">
<meta name="code_language" content="c#">
<meta name="vs_defaultclientscript" content="javascript">
<meta name="vs_targetschema" content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body ms_positioning="gridlayout">
<form id="form1" method="post" runat="server">
<iframe style="width:100%;height:100%" src="schedulerjob/schedulerjob.txt"></iframe>
</form>
</body>
</html>

对工程进行编译并运行,就可以看到结果了,结果如下:

计划任务测试开始:
2003-13-10 11:08:15
2003-13-10 11:08:18
2003-13-10 11:08:21
2003-13-10 11:08:24
2003-13-10 11:08:27
2003-13-10 11:08:30 

需要说明的是,以上只是在web应用程序中执行计划任务的简单例子,对于多个任务来说,需要在不同的线程内进行工作,对计划的安排也是很简单的,实际还需要站点堵塞,当机的情况。另外这里也没有进行错误的处理等工作,相信大家会写出更加完美的代码的。

点击下载源码:

资源回收,当web没有人访问的时候,定时器会回收停掉
不知道在 application_end 时自动访问一次有用么,我这前测试了几天这个方法都可以行。

复制代码 代码如下:

void application_end(object sender, eventargs e)
{
///在应用程序关闭时运行的代码
websocket.stop();
thread.sleep(15000);
try
{
string url = "http://127.0.0.1/404.aspx?mater=" + datetime.now.ticks;
httpwebrequest httpwebrequest = (httpwebrequest)httpwebrequest.create(url);
using (httpwebresponse response = (httpwebresponse)httpwebrequest.getresponse())
{
stream resstream = response.getresponsestream();
}
}
catch (exception ex)
{
//异常时,等15s,再访问一次。
thread.sleep(15000);
string url = "http://127.0.0.1/404.aspx?mater=" + datetime.now.ticks;
httpwebrequest httpwebrequest = (httpwebrequest)httpwebrequest.create(url);
using (httpwebresponse response = (httpwebresponse)httpwebrequest.getresponse())
{
stream resstream = response.getresponsestream();
}

hangjing.applog.applog.error("application_end:" + ex);
}
}

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网