This works. Wallet can stay locked and 5000 addresses will be generated. It is completely safe, even server is hacked.
After that you need to unlock the wallet so another 5000 addresses to be pre-generated. However, this step is not completely safe. Suppose server is hacked and someone got the password via key logger.
Another possibility is... when ...
If for you it's ok to use 3rd parties' services, a simple google search will present to you several plug-ins that suit your purpose.
If you want to do it by yourself, here is how you may want to tackle this endevour:
you must have an HD wallet (aka deterministic wallet compliant with BIP 32).
you put your XPUB in your server and you use it to generate ...