I am cretaing Timer at runtime in Gloabl.asax file,I add event handler for Timer Tick Event,But it never calls to handled function.

if any body know how to use timer in global.asax file in asp.net with c#.net ,which uns after every one mintue ,then please help me.
its very urgent.

Dani AI

Generated

— common reasons a timer created in Global.asax never fires, and a robust pattern to fix it.

Timers started in Global.asax often fail because of one or more of these issues: a UI timer (e.g., System.Windows.Forms.Timer) was used in a server process, the timer was created in a local variable and garbage-collected, the event was not wired before the timer was enabled, or the IIS app domain recycled/was idle so the process never stayed alive. Moving the thread (as suggested) only changes the forum location, not the runtime behavior.

A safer, production-friendly approach is to register a background object with the hosting environment and use a ThreadPool timer. The example below shows the minimal pattern (register, start a System.Threading.Timer, avoid overlapping runs, unregister on shutdown):

using System;
using System.Threading;
using System.Web.Hosting;

public class GlobalScheduler : IRegisteredObject
{
    private Timer _timer;
    private readonly object _lock = new object();
    private volatile bool _stopping;

    public GlobalScheduler()
    {
        HostingEnvironment.RegisterObject(this);
        _timer = new Timer(Callback, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
    }

    private void Callback(object state)
    {
        if (_stopping) return;
        if (!Monitor.TryEnter(_lock)) return;
        try
        {
            // background work here — do NOT use HttpContext.Current
        }
        catch (Exception) { /* log errors */ }
        finally { Monitor.Exit(_lock); }
    }

    public void Stop(bool immediate)
    {
        _stopping = true;
        _timer?.Dispose();
        HostingEnvironment.UnregisterObject(this);
    }
}

Troubleshooting notes: keep the timer reference as a field (not a local), do not use UI timers, catch/log exceptions inside the callback, avoid HttpContext.Current, and prevent overlapping runs with locks or by changing the timer. For reliable scheduled work in production, prefer an external scheduler (Windows Service, scheduled task, a background-job library such as Hangfire, or cloud job services) or, for ASP.NET Core, implement IHostedService/BackgroundService instead of Global.asax timers.

Recommended Answers

All 2 Replies

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.