Skip to content

Instantly share code, notes, and snippets.

@DuoSRX
Last active May 6, 2021 07:54
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save DuoSRX/8f3290d3d93e0054fe35 to your computer and use it in GitHub Desktop.
Enqueue Sidekiq jobs from Go
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