Handle signals in artisan commands

Overview

Handle signals in artisan commands

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Using this package you can easily handle signals like SIGINT, SIGTERM in your Laravel app.

Here's a quick example where the SIGINT signal is handled.

use Spatie\SignalAwareCommand\SignalAwareCommand;

class YourCommand extends SignalAwareCommand
{
    protected $signature = 'your-command';

    public function handle()
    {
        $this->info('Command started...');

        sleep(100);
    }

    public function onSigint()
    {
        // will be executed when you stop the command
    
        $this->info('You stopped the command!');
    }
}

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-signal-aware-command

Usage

In order to make an Artisan command signal aware you need to let it extend SignalAwareCommand.

use Spatie\SignalAwareCommand\SignalAwareCommand;

class YourCommand extends SignalAwareCommand
{
    // your code
}

Handling signals

There are three ways to handle signals:

  • on the command itself
  • via the Signal facade
  • using the SignalReceived event

On the command

To handle signals on the command itself, you need to let your command extend SignalAwareCommand. Next, define a method that starts with on followed by the name of the signal. Here's an example where the SIGINT signal is handled.

use Spatie\SignalAwareCommand\SignalAwareCommand;

class YourCommand extends SignalAwareCommand
{
    protected $signature = 'your-command';

    public function handle()
    {
        $this->info('Command started...');

        sleep(100);
    }

    public function onSigint()
    {
        // will be executed when you stop the command
    
        $this->info('You stopped the command!');
    }
}

Via the Signal facade

Using the Signal facade you can register signal handling code anywhere in your app.

First, you need to define the signals you want to handle in your command in the handlesSignals property.

use Spatie\SignalAwareCommand\SignalAwareCommand;

class YourCommand extends SignalAwareCommand
{
    protected $signature = 'your-command';
    
    protected $handlesSignals = [SIGINT];

    public function handle()
    {
        (new SomeOtherClass())->performSomeWork();

        sleep(100);
    }
}

In any class you'd like you can use the Signal facade to register code that should be executed when a signal is received.

use Illuminate\Console\Command;
use Spatie\SignalAwareCommand\Facades\Signal;

class SomeOtherClass
{
    public function performSomeWork()
    {
        Signal::handle(SIGINT, function(Command $commandThatReceivedSignal) {
            $commandThatReceivedSignal->info('Received the SIGINT signal!');
        })
    }
}

You can call clearHandlers if you want to remove a handler that was previously registered.

use Spatie\SignalAwareCommand\Facades\Signal;

public function performSomeWork()
{
    Signal::handle(SIGNINT, function() {
        // perform cleanup
    });
    
    $this->doSomeWork();
    
    // at this point doSomeWork was executed without any problems
    // running a cleanup isn't necessary anymore
    Signal::clearHandlers(SIGINT);
}

To clear all handlers for all signals use Signal::clearHandlers().

Using the SignalReceived event

Whenever a signal is received, the Spatie\SignalAwareCommand\Events\SignalReceived event is fired.

To register which events you want to receive you must define a handlesSignals property on your command. Here's an example where we register listening for the SIGINT signal.

use Spatie\SignalAwareCommand\SignalAwareCommand

class YourCommand extends SignalAwareCommand
{
    protected $signature = 'your-command';
    
    protected $handlesSignals = [SIGINT];

    public function handle()
    {
        (new SomeOtherClass())->performSomeWork();

        sleep(100);
    }
}

In any class you'd like you can listen for the SignalReceived event.

use Spatie\SignalAwareCommand\Events\SignalReceived;
use Spatie\SignalAwareCommand\Signals;

class SomeOtherClass
{
    public function performSomeWork()
    {
        Event::listen(function(SignalReceived $event) {
            $signalNumber = $event->signal;
            
            $signalName = Signals::getSignalName($signalNumber);
        
            $event->command->info("Received the {$signalName} signal");
        });
    }
}

Learn how this package was built

The foundations of this pacakge were coded up in this live stream on YouTube.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

You might also like...
Helper commands for Laravel Beyond Crud

About beyond-crud-helpers This package has many helper commands for the Laravel BEyond CRUD project by Spatie Installation composer require --dev tarr

A PocketMine-MP plugin which allows the users to edit no permission message of commands
A PocketMine-MP plugin which allows the users to edit no permission message of commands

CommandPermissionMessage A PocketMine-MP plugin which allows the users to edit no permission message of commands Have you ever got bored by the red me

A Cli tool to save you time, and gives you the power to scaffold all of your models,controllers,commands
A Cli tool to save you time, and gives you the power to scaffold all of your models,controllers,commands

A Cli tool to save you time, and gives you the power to scaffold all of your models,controllers,commands... at once Installation You can install the p

Hentai Bash - This is the core of Hentai Terminal, responsible for the basic functions and commands
Hentai Bash - This is the core of Hentai Terminal, responsible for the basic functions and commands

Hentai Bash - This is the core of Hentai Terminal, responsible for the basic functions and commands. It is mainly used for writing and executing commands.

YCOM Impersonate. Login as selected YCOM user πŸ§™β€β™‚οΈin frontend.

YCOM Impersonate Login as selected YCOM user in frontend. Features: Backend users with admin rights or YCOM[] rights, can be automatically logged in v

Dispatcher is a Laravel artisan command scheduling tool used to schedule artisan commands within your project so you don't need to touch your crontab when deploying.
Dispatcher is a Laravel artisan command scheduling tool used to schedule artisan commands within your project so you don't need to touch your crontab when deploying.

Dispatcher Dispatcher allows you to schedule your artisan commands within your Laravel project, eliminating the need to touch the crontab when deployi

Dispatcher is a Laravel artisan command scheduling tool used to schedule artisan commands within your project so you don't need to touch your crontab when deploying.
Dispatcher is a Laravel artisan command scheduling tool used to schedule artisan commands within your project so you don't need to touch your crontab when deploying.

Dispatcher Dispatcher allows you to schedule your artisan commands within your Laravel project, eliminating the need to touch the crontab when deployi

πŸ“ Artisan Menu - Use Artisan via an elegant console GUI
πŸ“ Artisan Menu - Use Artisan via an elegant console GUI

πŸ“ Artisan Menu Use Artisan via an elegant console GUI Features Run built-in and custom Artisan commands from a console GUI Prompts to enter required

πŸ“ Artisan Menu - Use Artisan via an elegant console GUI
πŸ“ Artisan Menu - Use Artisan via an elegant console GUI

πŸ“ Artisan Menu Use Artisan via an elegant console GUI Features Run built-in and custom Artisan commands from a console GUI Prompts to enter required

A package for adding loading spinners to your Laravel Artisan commands
A package for adding loading spinners to your Laravel Artisan commands

Table of Contents Overview Installation Requirements Install the Package Usage Adding Loading Spinners to Commands Adding Text to the Spinner Customis

 Execute Artisan commands on remote servers
Execute Artisan commands on remote servers

Execute Artisan commands on remote servers This package provides a command to execute Artisan command on a remote server. Here's an example that will

This package adds artisan commands to create VueJS components and InertiaJS components.
This package adds artisan commands to create VueJS components and InertiaJS components.

Laravel Vue Commands This package adds artisan commands to create VueJS components and InertiaJS components. Installation You can install the package

Simple but yet powerful library for running almost all artisan commands.
Simple but yet powerful library for running almost all artisan commands.

:artisan gui Simple but yet powerful library for running some artisan commands. Requirements Laravel 8.* php ^7.3 Installation Just install package: c

A package that makes it easy to have the `artisan make:` commands open the newly created file in your editor of choice.

Open On Make A package that makes it easy to have the artisan make: commands open the newly created file in your editor of choice. Installation compos

Package for Laravel that gives artisan commands to setup and edit environment files.
Package for Laravel that gives artisan commands to setup and edit environment files.

Setup and work with .env files in Laravel from the command line NOTE: This doesn't work with Laravel 5 since .env files were changed. This is for Lara

A bookmarkable, searchable cheatsheet for all of Laravel's default Artisan commands.

artisan.page A bookmarkable, searchable cheatsheet for all of Laravel's default Artisan commands. Generation The generation of the manifest files is d

Laravel API architecture builder based on artisan commands.

πŸ§‘β€πŸ”¬ API-Formula Laravel API architecture builder based on artisan commands. This package provides a nice and fluent way to generate combined control

This Laravel Nova tool lets you run artisan and bash commands directly from Nova 4 or higher.
This Laravel Nova tool lets you run artisan and bash commands directly from Nova 4 or higher.

Laravel Nova tool for running Artisan & Shell commands. This Nova tool lets you run artisan and bash commands directly from nova. This is an extended

Execute Laravel Artisan commands via REST APIs and HTTP requests safely.

Artisan Api There might be some times you wanted to execute an Artisan command, but you did not have access to shell or SSH. Here we brought REST API

Releases(1.2.0)
Owner
Spatie
We create products and courses for the developer community
Spatie
Backup your laravel database by a simple artisan command

Backup your laravel database by a simple artisan command This package will allow you to backup your laravel app database and you can also choose to se

Mohammed Omer 23 Feb 10, 2022
Customized loading βŒ› spinner for Laravel Artisan Console.

Laravel Console Spinner Laravel Console Spinner was created by Rahul Dey. It is just a custom Progress Bar inspired by icanhazstring/symfony-console-s

Rahul Dey 71 Oct 26, 2022
[ABANDONED] PHP library for executing commands on multiple remote machines, via SSH

#Shunt Inspired by Ruby's Capistrano, Shunt is PHP library for executing commands on multiple remote machines, via SSH. Specifically, this library was

The League of Extraordinary Packages 436 Feb 20, 2022
Library for creating CLI commands or applications

Console Motivation: this library purpose is to provide a lighter and more robust API for console commands and/or applications to symfony/console. It c

ThΓ©o FIDRY 16 Dec 28, 2022
A developer-friendly wrapper around execution of shell commands.

ptlis/shell-command A developer-friendly wrapper around execution of shell commands. There were several goals that inspired the creation of this packa

brian ridley 18 Dec 31, 2022
A package built for lumen that ports most of the make commands from laravel.

A package built for lumen that ports most of the make commands from laravel. For lumen v5.1, but will most likely work for 5.2 as well. I haven't tested. If you have requests, let me know, or do it yourself and make a pull request

Michael Bonds 22 Mar 8, 2022
Supercharge your Symfony console commands!

zenstruck/console-extra A modular set of features to reduce configuration boilerplate for your commands: /** * Creates a user in the database. * *

Kevin Bond 29 Nov 19, 2022
A simple object oriented interface to execute shell commands in PHP

php-shellcommand php-shellcommand provides a simple object oriented interface to execute shell commands. Installing Prerequisites Your php version mus

Michael HΓ€rtl 283 Dec 10, 2022
PHP library for executing commands on multiple remote machines, via SSH

#Shunt Inspired by Ruby's Capistrano, Shunt is PHP library for executing commands on multiple remote machines, via SSH. Specifically, this library was

The League of Extraordinary Packages 436 Feb 20, 2022
πŸ€– GitHub Action to run symfony console commands.

Symfony Console GitHub Action Usage You can use it as a Github Action like this: # .github/workflows/lint.yml name: "Lint" on: pull_request: push

Nucleos 3 Oct 20, 2022