简体   繁体   中英

asp.net timer not working

I am new to aspx and can not get my web timer to work. What am I missing here? Also DebugSet.logoutTime = 1800000 and DebugSet.logotWarnings = 3. The user is to be warned every minute before they are logged out of the system. These settings will be raised before the release, I just lowered them for testing purposes.

public partial class test : System.Web.UI.Page
{
    private LoggedUser _User;
    private Timer LogoutTimer;
    private int TmCnt = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        _User = new LoggedUser(true);
        SetTimer();
    }
    private void SetTimer()
    {
        LogoutTimer = new Timer();
        LogoutTimer.Interval = DebugSet.logoutTime/DebugSet.logoutWarnings;
        LogoutTimer.Tick += new EventHandler<EventArgs>(LogoutTimer_Tick);
        LogoutTimer.Enabled = true;
        LogoutTimer.ViewStateMode = ViewStateMode.Enabled;
    }
    private void LogoutTimer_Tick(object sender, EventArgs e)
    {
        TmCnt++;
        if (TmCnt == DebugSet.logoutWarnings)
        {
            _User.UserLoggedIn = false;
            _User.SetSessions();
            LogoutTimer.Enabled = false;
            HttpContext.Current.Session["FCSWarning"] = "LoggedOut";
            Response.Redirect("../Views/index.aspx");
        }
        else
        {
            int i = (DebugSet.logoutTime / (1000 * 60)) - ((DebugSet.logoutTime / (1000 * 60)) * TmCnt);
            string msg = "<Script language=javascript>alert('You will be logged out in " + i.ToString() + " min. due to inactivity.');</Script>";
            Response.Write(msg);
        }
    }
}

You are using a winforms timer (I think). With websites all instances of variables and classes are destroyed when the page is send to the browser (garbage collection). So LogoutTimer only exists for a very short time. You need to use the Timer control.

https://msdn.microsoft.com/en-us/library/bb386404.aspx

You should know this also when working with websites, the Page Life Cycle:

https://msdn.microsoft.com/en-us/library/ms178472.aspx

The ASP.NET Timer is an ASP.NET control. Each ASP.NET control must be added into a page control hierarchy, otherwise, it won't operate correctly or won't operate at all.

Add your Timer to page control hierarchy:

LogoutTimer = new Timer();
LogoutTimer.ID = "MyTimer";
this.Controls.Add(LogoutTimer);
LogoutTimer.Interval = DebugSet.logoutTime/DebugSet.logoutWarnings;
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM