Merge pull request #9 from acaloiaro/more-suggestions

More suggestions
This commit is contained in:
Juan C. Müller 2023-02-23 21:42:38 -05:00 committed by GitHub
commit b0fc2943af
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 26 additions and 20 deletions

View file

@ -31,7 +31,7 @@ func main() {
}, neoq.HandlerConcurrency(8))
// Option 2: Set options after the handler is created
handler = handler.WithOption(neoq.HandlerConcurrency(8))
handler.WithOptions(neoq.HandlerConcurrency(8))
err = nq.Listen(ctx, queue, handler)
if err != nil {

View file

@ -35,7 +35,7 @@ func main() {
})
// this 10ms deadline will cause our job that sleeps for 1s to fail
handler = handler.WithOption(neoq.HandlerDeadline(10 * time.Millisecond))
handler.WithOptions(neoq.HandlerDeadline(10 * time.Millisecond))
err = nq.Listen(ctx, queue, handler)
if err != nil {

View file

@ -20,9 +20,10 @@ func main() {
log.Println("running periodic job")
return
})
handler = handler.
WithOption(neoq.HandlerDeadline(500 * time.Millisecond)).
WithOption(neoq.HandlerConcurrency(1))
handler.WithOptions(
neoq.HandlerDeadline(500*time.Millisecond),
neoq.HandlerConcurrency(1),
)
nq.ListenCron(ctx, "* * * * * *", handler)

21
neoq.go
View file

@ -93,10 +93,11 @@ type Handler struct {
// HandlerOption is function that sets optional configuration for Handlers
type HandlerOption func(w *Handler)
// WithOption returns the handler with the given options set
func (h Handler) WithOption(opt HandlerOption) (handler Handler) {
opt(&h)
return h
// WithOptions sets one or more options on handler
func (h Handler) WithOptions(opts ...HandlerOption) {
for _, opt := range opts {
opt(&h)
}
}
// HandlerDeadline configures handlers with a time deadline for every executed job
@ -127,17 +128,19 @@ func MaxQueueCapacity(capacity int64) HandlerOption {
// NewHandler creates a new queue handler
func NewHandler(f HandlerFunc, opts ...HandlerOption) (h Handler) {
h = Handler{
handle: f,
concurrency: runtime.NumCPU() - 1,
handle: f,
}
for _, opt := range opts {
opt(&h)
h.WithOptions(opts...)
// default to running one fewer threads than CPUs
if h.concurrency == 0 {
HandlerConcurrency(runtime.NumCPU() - 1)(&h)
}
// always set a job deadline if none is set
if h.deadline == 0 {
h.deadline = DefaultHandlerDeadline
HandlerDeadline(DefaultHandlerDeadline)(&h)
}
return

View file

@ -31,9 +31,10 @@ func TestWorkerListenConn(t *testing.T) {
done <- true
return
})
handler = handler.
WithOption(HandlerDeadline(500 * time.Millisecond)).
WithOption(HandlerConcurrency(1))
handler.WithOptions(
HandlerDeadline(500*time.Millisecond),
HandlerConcurrency(1),
)
if err != nil {
t.Error(err)
@ -97,9 +98,10 @@ func TestWorkerListenCron(t *testing.T) {
return
})
handler = handler.
WithOption(HandlerDeadline(500 * time.Millisecond)).
WithOption(HandlerConcurrency(1))
handler.WithOptions(
HandlerDeadline(500*time.Millisecond),
HandlerConcurrency(1),
)
if err != nil {
t.Error(err)