Home > Software design >  Does symfony event listeners also have limited execution time?
Does symfony event listeners also have limited execution time?

Time:10-25

I want to run heavy load to hash passwords of users after the kernel terminate.

I have this in controller:

public function insert(Request $request): Response
{
    ...

    // listener to update passwords
    $this->eventDispatcher->addListener(KernelEvents::TERMINATE, function () use ($users) {
        foreach ($users as $user) {
            $this->hashPassword($user); //for 100 users will take 40 seconds
        }
    });


    return $this->redirectToRoute('some_route');
}

User is redirected to new route and passwords are hashed in database. But the problem is not all passwords are hashed. It seems it stops half way.

Is it something to do with execution time ? If yes how can I bypass it ? without changing php execution time.

Thanks.

CodePudding user response:

Your problem means that execution time is stopping your process AND your storage engine doesn't respect ACID(atomicity, coherence, isolation and durability) properties. Your requests aren't secured with a transaction.

First of all, I suggest you to use a transaction and commit it at the end of process, because it's very dangerous to only update some data.

Then, a "bad" solution is to increase execution time.

But a best solution is to use asynchrone messages. You can dispatch async message with Symfony Messenger. The Symfony Book written by Fabien Potencier explain how to do it in this chapter. Fabien show us how to check if message is a spam. Instead of checking messages, you only have to hash all unhashed passwords. In this messenger, it isn't dangerous to increase execution time.

  • Related