Last active
May 6, 2021 07:54
-
-
Save DuoSRX/8f3290d3d93e0054fe35 to your computer and use it in GitHub Desktop.
Enqueue Sidekiq jobs from Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/rand" | |
"encoding/hex" | |
"encoding/json" | |
"fmt" | |
"github.com/garyburd/redigo/redis" | |
"io" | |
"time" | |
) | |
type Job struct { | |
JID string `json:"jid"` | |
Retry bool `json:"retry"` | |
Queue string `json:"queue"` | |
Class string `json:"class"` | |
Args []string `json:"args"` | |
EnqueuedAt int64 `json:"enqueued_at"` | |
} | |
func randomHex(n int) string { | |
id := make([]byte, n) | |
io.ReadFull(rand.Reader, id) | |
return hex.EncodeToString(id) | |
} | |
func (job *Job) Enqueue() string { | |
conn, err := redis.Dial("tcp", ":6379") | |
if err != nil { | |
panic(err) | |
} | |
encoded, _ := json.Marshal(job) | |
conn.Send("SADD", "queues", job.Queue) | |
conn.Send("LPUSH", "queue:"+job.Queue, string(encoded)) | |
conn.Flush() | |
conn.Close() | |
return job.JID | |
} | |
func NewJob(class, queue string, args []string) *Job { | |
job := &Job{ | |
JID: randomHex(12), | |
Retry: false, | |
Queue: queue, | |
Class: class, | |
Args: args, | |
EnqueuedAt: time.Now().Unix(), | |
} | |
return job | |
} | |
func main() { | |
job := NewJob("HardWorker", "default", []string{"foo"}) | |
fmt.Println(job.Enqueue()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment