Using ApplicationState in Reccuring jobs

recurring
Tags: #<Tag:0x00007f49a0b43e08>

#1

i am using ApplicationState variable inside recurring job,it thows an exception ,ApplicationState is null,can anybody help?
.RecurringJob.AddOrUpdate(
() => Fun1()(),
Cron.Minutely);

public Fun1()
{

//some processin here
//Response =some intialisation

                HttpContext.Current.Application["DateAndTime"] = Response;
           



        }

#2

Yes, this is by design as Hangfire does not have any dependencies on HTTP. Hangfire may be hosted as within a aspnet[core] application, but the process/jobs are run outside of an HTTP context.

There are a couple of ways to solve this

  1. create an object to represent the data you want and create a singleton of your object. Effectively copying the values you want from application state to a static object/value. This way Hangfire can access the value in-memory without the knowledge of where the value came from
  2. pass the parameter as an argument to the reoccurring job when the application starts

#3

But I need to update state variable Everytime.I am getting values from an external Api and update the state .


#4

You will need to store the value somewhere other than HTTP. An intermediate storage location. whether that’s in memory, or some persistence store.


#5

public static class DateAndTimeState
{
private static DateAndTimeResponse _dateAndTimeResponse=null;

    public static DateAndTimeResponse dateAndTimeResponse
    {
        get { return _dateAndTimeResponse; }
        set {
            if(_dateAndTimeResponse!=null)
            {
                lock (_dateAndTimeResponse)
                {
                    _dateAndTimeResponse = value;
                }
            }
            else
            {
                
                    _dateAndTimeResponse = value;
                
            }
            
            
        }
    }

}

will this work fine in mvc