1

So i want to create a script that delete folder and it's content, but while doing this there may be created new files. What is the best way to do this?

Some example is - we have "cache" folder and i want to delete the whole cache, but while doing this there are more files created in the cache folder and it's never empty so that it could not be deleted.

1 Answer 1

2

Move the directory out of place (to /tmp for example). Then delete it. Moves are atomic, and quick (since it's just a pointer change on the filesystem and doesn't really involve heavy disk I/O regardless of what's in the folder).

For the best resilience against any type of issue, you should create a directory structure like this:

/var/www/website/
    releases/
        1111/
        1112/
        1113/
    current_release/

Let's say that your website is currently in /var/www/website/releases/1113/. Your apache should be setup with a DocumentRoot of /var/www/website/current_release/ which is symlinked to /var/www/website/releases/1113

When you need to clear your cache, what you should do is deploy a new release, such as /var/www/website/releases/1114. When ti is deployed, and has an empty cache directory, flip the symlink on /var/www/website/current_release/ to your new releases directory.

Apache will then serve files out of the new directory with an empty cache folder.

This is the only truly atomic way to accomplish things like this, other than taking the server offline (which usually isn't an option for something as trivial as clearing cache).

This would be a sort of enterprise-level solution to the problem, but it carries the added benefit of allowing you to easily roll back your production server as well (just switch the symlink to the previous version). It may seem like over-engineering if you're very concerned about the issue, this is the right way.

Sign up to request clarification or add additional context in comments.

4 Comments

so does this mean that i can move it and it will be created again without problem if a file is created while the move is done
A file won't be created while the move is done. But let me flesh out my answer a little more since this seems to be quite important.
thanks very much for the solution, but so to clear that i understand the answear. What i need is to use "rename" like rename("cache", "tmp/"). Than in tmp empty it and than do the reverse action and rename("tmp/", "cache")
so i was wrong i saw the symlink() function but i also so that for windows it works for vista +, will it be a problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.