Click here to Skip to main content
15,921,716 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm new to C# programming and I cannot figure out how can I trigger a function to be executed every hour. The function is located in one of my controllers.

The only way I found in the internet is to call it from Global.asax.cs file but it doesn't work.

Can somebody help me please with this?
C#
public class WebApiApplication : System.Web.HttpApplication
{
    private static Timer timer;
    protected void Application_Start()
    {
        // AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        //WebApiConfig.Register(GlobalConfiguration.Configuration);

        timer = new System.Timers.Timer(10000);
        var SSSData = new SSSData();

        timer.Elapsed += new ElapsedEventHandler(RedirectToAction("DoPushSend", "Notification", new
        {
            dataSSS = SSSData
        }));
        timer.Interval = 3600000;
        timer.Enabled = true;
    }
}

public static void DoPushSend(SSSData dataSSS)
{
    client.BaseAddress = new Uri("sample.com/3/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    try
    {
        string url = "sample.com/device/";
        WebClient client = new WebClient();
        string content = client.DownloadString(url);
        List<string> expoTokens = JsonConvert.DeserializeObject<list<string>>(content);

        var expoSDKClient = new PushApiClient();
        var pushTicketReq = new PushTicketRequest()
        {
            PushTo = expoTokens,
            PushBadgeCount = 7,
            PushBody = dataSSS.DESCRIPTION + "[<$>]" + dataSSS.LAT + "[<$>]" + dataSSS.LON + "[<$>]" + dataSSS.MAXRADIUS
        };

        int nowTimeTo = DateTime.Compare(DateTime.Now, dataSSS.TIMETO);
        int nowTimeFrom = DateTime.Compare(DateTime.Now, dataSSS.TIMEFROM);

        if (nowTimeFrom >= 0)
        {
            if (nowTimeTo <= 0)
            {
                var result = expoSDKClient.PushSendAsync(pushTicketReq).GetAwaiter().GetResult();
            }
        }
    }
    catch (Exception e)
    {
        SSS_Common.Helpers.ErrorHelper.WriteToLog("Notification : ", e);
    }
}


What I have tried:

The only way I found in the internet is to call it from Global.asax.cs file but it doesn't work.
Posted
Updated 13-Sep-20 23:40pm
v2

There could be multiple ways to do it:
1. Timer
2. Quartz
3. Windows Service

References:
Simple task Scheduling using Global asax[^]
Run a piece of code once a day automatically in asp MVC | The ASP.NET Forums[^]
c# - Call Function After a specific intervel - Stack Overflow[^]
Tutorial: Create a Windows service app | Microsoft Docs[^]

In your setup, seems Timer could be lesser work to embed - something similar to what you are trying:
1. Use Application_Start
2. Setup timer in it
3. Via timer, setup what you want to do at regular interval
References above shares examples on how to do it.


Try out the one that suits you best. Generally, something like every hour job run suits more for Windows Service.
 
Share this answer
 
Comments
Member 11697488 14-Sep-20 5:42am    
Can you please provide me a snippet of how can I fix my code, because I couldn't understand what you mean
Sandeep Mewara 14-Sep-20 5:45am    
Above references has what you are trying. Did you look at them? try that and see please.

Keep things simple to start with:
1. first have something basic as timer based (use 30 second or 1 min timer for some logging or message)
2. once you have the setup, now add your specific every hour core logic
Member 11697488 14-Sep-20 5:46am    
I've looked at them, but don't know how to implement them in my code. I'm quite new in C#, sorry
Sandeep Mewara 14-Sep-20 5:54am    
You need to attempt and try. As shared, break the problem into smaller chunks and move ahead. This is how you will learn too.
Member 11697488 14-Sep-20 5:57am    
Already tried. I really need your help, please
You should use a Windows service, combined with a web service (or WebAPI app) for something like this. The windows service would simply be the timer, which would call the web service to do it's thing at the specified interval.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900