在C#中每2分钟执行一次功能(Web应用程序) [英] execute function after every 2 min in C# (Web application)

查看:656
本文介绍了在C#中每2分钟执行一次功能(Web应用程序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用系统;
使用System.Timers;

using System;
using System.Timers;

public partial class copy_option : System.Web.UI.Page
{
    private System.Timers.Timer aTimer;
    protected void Page_Load(object sender, EventArgs e)
    {
        // Create a timer with a two second interval.
        aTimer = new System.Timers.Timer(120000);
        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += OnTimer;
        aTimer.Enabled = true;
    }

    public void OnTimer(Object source, ElapsedEventArgs e)
    {
        importdatafromexcel(excelfilepath);
    }
}




伙计们,

我想每隔2分钟运行一次"importdatafromexcel"函数,但是如果运行上述代码,则该函数每分钟被调用两次.请让我知道需要进行哪些更改.




Guys,

I wanted to run "importdatafromexcel" a function, after every 2 minutes but if I run the above code, the function was called twice for every minute. Please let me know what changes needs to be done.

推荐答案

问题是您对Web应用程序的了解...
这样的应用程序是分开运行的,这意味着其中有服务器和客户端部分...
实际发生的情况是您的页面开始并在服务器上创建计时器(然后在服务器上),然后进入页面渲染的最后阶段,之后它死了(卸载),计时器也随之消失了.
这是您必须考虑您的解决方案,并首先考虑为什么要尝试这样做的关键!!!
我之所以这么说是因为这样的重复操作不适用于Web应用程序...创建某种服务可能会更好...
想了以后...
System.Web.UI命名空间中还有另一个计时器类可以解决您的问题...它有一个服务器广告,客户端在服务器端一起工作,即使服务器上的页面消失(使用JavaScript),计时器也可以保持活动状态...
https://msdn.microsoft.com/zh-cn/library/system.web.ui.timer%28v = vs.110%29.aspx [
The problem is your understanding of web applications...
Such an application runs separated, means that there is a server and a client part of it...
What actually happening is that your page starts and creates the timer (on the server), than gets into the final phase of the page rendering, after which it dies!(unloads) and with it the timer too...
This is the point that you have to think about your solution, and to think about why at the first place you try to do such a thing!!!
I''m saying you this because such repeating action does not fit good into a web application...It may be better to create some sort of service...
After you have thinking about it...
There is an other timer class inside System.Web.UI namespace that came to solve your problem...It has a server ad a client side that wotk together to keep the timer alive even after the page on the server gone (using JavaScript)...
https://msdn.microsoft.com/en-us/library/system.web.ui.timer%28v=vs.110%29.aspx[^]


这篇关于在C#中每2分钟执行一次功能(Web应用程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆