Step 24: Running Crons

Running Crons

Crons are useful to do maintenance tasks. Unlike workers, they run on a schedule for a short period of time.

Cleaning up Comments

Comments marked as spam or rejected by the admin are kept in the database as the admin might want to inspect them for a little while. But they should probably be removed after some time. Keeping them around for a week after their creation is probably enough.

Create some utility methods in the comment repository to find rejected comments, count them, and delete them:

patch_file

  1. --- a/src/Repository/CommentRepository.php
  2. +++ b/src/Repository/CommentRepository.php
  3. @@ -6,6 +6,7 @@ use App\Entity\Comment;
  4. use App\Entity\Conference;
  5. use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  6. use Doctrine\Persistence\ManagerRegistry;
  7. +use Doctrine\ORM\QueryBuilder;
  8. use Doctrine\ORM\Tools\Pagination\Paginator;
  9. /**
  10. @@ -16,6 +17,8 @@ use Doctrine\ORM\Tools\Pagination\Paginator;
  11. */
  12. class CommentRepository extends ServiceEntityRepository
  13. {
  14. + private const DAYS_BEFORE_REJECTED_REMOVAL = 7;
  15. +
  16. public const PAGINATOR_PER_PAGE = 2;
  17. public function __construct(ManagerRegistry $registry)
  18. @@ -23,6 +26,29 @@ class CommentRepository extends ServiceEntityRepository
  19. parent::__construct($registry, Comment::class);
  20. }
  21. + public function countOldRejected(): int
  22. + {
  23. + return $this->getOldRejectedQueryBuilder()->select('COUNT(c.id)')->getQuery()->getSingleScalarResult();
  24. + }
  25. +
  26. + public function deleteOldRejected(): int
  27. + {
  28. + return $this->getOldRejectedQueryBuilder()->delete()->getQuery()->execute();
  29. + }
  30. +
  31. + private function getOldRejectedQueryBuilder(): QueryBuilder
  32. + {
  33. + return $this->createQueryBuilder('c')
  34. + ->andWhere('c.state = :state_rejected or c.state = :state_spam')
  35. + ->andWhere('c.createdAt < :date')
  36. + ->setParameters([
  37. + 'state_rejected' => 'rejected',
  38. + 'state_spam' => 'spam',
  39. + 'date' => new \DateTime(-self::DAYS_BEFORE_REJECTED_REMOVAL.' days'),
  40. + ])
  41. + ;
  42. + }
  43. +
  44. public function getCommentPaginator(Conference $conference, int $offset): Paginator
  45. {
  46. $query = $this->createQueryBuilder('c')

Tip

For more complex queries, it is sometimes useful to have a look at the generated SQL statements (they can be found in the logs and in the profiler for Web requests).

Using Class Constants, Container Parameters, and Environment Variables

7 days? We could have chosen another number, maybe 10 or 20. This number might evolve over time. We have decided to store it as a constant on the class, but we might have stored it as a parameter in the container, or we might have even defined it as an environment variable.

Here are some rules of thumb to decide which abstraction to use:

  • If the value is sensitive (passwords, API tokens, …), use the Symfony secret storage or a Vault;
  • If the value is dynamic and you should be able to change it without re-deploying, use an environment variable;
  • If the value can be different between environments, use a container parameter;
  • For everything else, store the value in code, like in a class constant.

Creating a CLI Command

Removing the old comments is the perfect task for a cron job. It should be done on a regular basis, and a little delay does not have any major impact.

Create a CLI command named app:comment:cleanup by creating a src/Command/CommentCleanupCommand.php file:

src/Command/CommentCleanupCommand.php

  1. namespace App\Command;
  2. use App\Repository\CommentRepository;
  3. use Symfony\Component\Console\Command\Command;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Input\InputOption;
  6. use Symfony\Component\Console\Output\OutputInterface;
  7. use Symfony\Component\Console\Style\SymfonyStyle;
  8. class CommentCleanupCommand extends Command
  9. {
  10. private $commentRepository;
  11. protected static $defaultName = 'app:comment:cleanup';
  12. public function __construct(CommentRepository $commentRepository)
  13. {
  14. $this->commentRepository = $commentRepository;
  15. parent::__construct();
  16. }
  17. protected function configure()
  18. {
  19. $this
  20. ->setDescription('Deletes rejected and spam comments from the database')
  21. ->addOption('dry-run', null, InputOption::VALUE_NONE, 'Dry run')
  22. ;
  23. }
  24. protected function execute(InputInterface $input, OutputInterface $output): int
  25. {
  26. $io = new SymfonyStyle($input, $output);
  27. if ($input->getOption('dry-run')) {
  28. $io->note('Dry mode enabled');
  29. $count = $this->commentRepository->countOldRejected();
  30. } else {
  31. $count = $this->commentRepository->deleteOldRejected();
  32. }
  33. $io->success(sprintf('Deleted "%d" old rejected/spam comments.', $count));
  34. return 0;
  35. }
  36. }

All application commands are registered alongside Symfony built-in ones and they are all accessible via symfony console. As the number of available commands can be large, you should namespace them. By convention, the application commands should be stored under the app namespace. Add any number of sub-namespaces by separating them by a colon (:).

A command gets the input (arguments and options passed to the command) and you can use the output to write to the console.

Clean up the database by running the command:

  1. $ symfony console app:comment:cleanup

Setting up a Cron on SymfonyCloud

One of the nice things about SymfonyCloud is that most of the configuration is stored in one file: .symfony.cloud.yaml. The web container, the workers, and the cron jobs are described together to help maintenance:

patch_file

  1. --- a/.symfony.cloud.yaml
  2. +++ b/.symfony.cloud.yaml
  3. @@ -52,6 +52,15 @@ hooks:
  4. (>&2 symfony-deploy)
  5. +crons:
  6. + comment_cleanup:
  7. + # Cleanup every night at 11.50 pm (UTC).
  8. + spec: '50 23 * * *'
  9. + cmd: |
  10. + if [ "$SYMFONY_BRANCH" = "master" ]; then
  11. + croncape symfony console app:comment:cleanup
  12. + fi
  13. +
  14. workers:
  15. messages:
  16. commands:

The crons section defines all cron jobs. Each cron runs according to a spec schedule.

The croncape utility monitors the execution of the command and sends an email to the addresses defined in the MAILTO environment variable if the command returns any exit code different than 0.

Configure the MAILTO environment variable:

  1. $ symfony var:set MAILTO=[email protected]

You can force a cron to run on your local machine:

  1. $ symfony cron comment_cleanup

Note that crons are set up on all SymfonyCloud branches. If you don’t want to run some on non-production environments, check the $SYMFONY_BRANCH environment variable:

  1. if [ "$SYMFONY_BRANCH" = "master" ]; then
  2. croncape symfony app:invoices:send
  3. fi

Going Further


This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.