bamzi / jobrunner

Framework for performing work asynchronously, outside of the request flow
MIT License
1.04k stars 99 forks source link

use Gin context inside job function #9

Closed calvinsug closed 6 years ago

calvinsug commented 6 years ago

I'm trying to implement jobrunner in my Gin-gonic framework and it works.

Problem is when i want to use gin context inside the function

jobrunner.Start() // optional: jobrunner.Start(pool int, concurrent int) (10, 1)
jobrunner.Schedule("@every 20s", CheckExpiredUrl{})

// Job Specific Functions type CheckExpiredUrl struct { // filtered }

func (e CheckExpiredUrl) Run() { // Queries the DB fmt.Println("Every 20 sec Check Expired Url") db := c.MustGet("db").(*mgo.Database) urls := []models.Url{} err := db.C(models.CollectionUrl).Find(nil).Sort("-expired_at").All(&urls) if err != nil { c.Error(err) } // do something with database } `

I need to use c *gin.Context

inside jobrunner function, and how to do that?

bamzi commented 6 years ago

Sorry for the delay. Since JobRunner is meant to be outside of the request flow, you can replicate the context by passing it through as such:

jobrunner.Schedule("@every 20s", CheckExpiredUrl{C:*gin.Context})

// Job Specific Functions
type CheckExpiredUrl struct {
   // you may need to go explicit and remove the pointer reference.
   C *gin.Context 

   // filtered
}
calvinsug commented 6 years ago

Hi, i have tried that, but it gives me an error: "type gin.Context is not an expression"

I have tried to remove the pointer like this code but still it gives me that error.

Here's my code: jobrunner.Schedule("@every 1h", checkExpiredUrl{Ctx:gin.Context})

type checkExpiredUrl struct { Ctx gin.Context }

bamzi commented 6 years ago

What part of gin.Context do you need for your program? Another way might be to instantiate the whole of *gin.Context (not best practice)


var ctx *gin.Context 

jobrunner.Schedule("@every 20s", CheckExpiredUrl{C:ctx})

// Job Specific Functions
type CheckExpiredUrl struct {
   // you may need to go explicit and remove the pointer reference.
   C *gin.Context 
   // filtered
}
calvinsug commented 6 years ago

i just want to get my stored values before like this:

c.Set("db", s.DB(db.Mongo.Database))

and get db key by this code: db := e.C.MustGet("db").(*mgo.Database)

bamzi commented 6 years ago

You don't seem to need the gin.Context, just pass the DB info explicitly

I'm going to close this thread since this is application specific and nothing to do with JobRunner.